登录
首页 >  Golang >  Go问答

函数接口的带有命名和非命名参数

来源:stackoverflow

时间:2024-02-26 23:12:26 328浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《函数接口的带有命名和非命名参数》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在学习 go 中的 protobuf 和 grpc。生成 pb.go 文件后

protoc --go_out=plugins=grpc:chat chat.proto

对于文件chat.proto

syntax = "proto3";
package chat;

message message {
  string body = 1;
}

service chatservice {
  rpc sayhello(message) returns (message) {}
}

生成的chat.pb.go有这2个接口:

type ChatServiceClient interface {
    SayHello(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)
}
...
type ChatServiceServer interface {
    SayHello(context.Context, *Message) (*Message, error)
}

我对 chatserviceclient 接口中命名参数的使用感到困惑。这些参数有没有用:ctxinopts。在这种情况下,我们什么时候应该使用命名参数和未命名参数?


解决方案


参数名称是可选的,在接口的情况下,它可能纯粹出于文档目的而提供。

Spec: Interfaces:

interfacetype      = "interface" "{" { ( methodspec | interfacetypename ) ";" } "}" .
methodspec         = methodname signature .

其中方法 Signature 是:

signature      = parameters [ result ] .
result         = parameters | type .
parameters     = "(" [ parameterlist [ "," ] ] ")" .
parameterlist  = parameterdecl { "," parameterdecl } .
parameterdecl  = [ identifierlist ] [ "..." ] type .

如您所见,parameterdecl 中的 identifierlist 位于方括号中,这意味着它是可选

想一个这样的例子:

type filemover interface {
    movefile(dst, src string) error
}

它“响亮而清晰”。如果我们省略参数名称怎么办?

type FileMover interface {
    MoveFile(string, string) error
}

第一个参数是否标识源或目标并不明显。提供 dstsrc 名称​​文档,就可以清楚地表明这一点。

当你实现一个接口并提供方法的实现时,如果你想引用参数,你必须命名它们,因为你通过它们的名字引用它们,但如果你不想引用到参数,即使这样它们也可以被省略。

查看相关问题:Is unnamed arguments a thing in Go?

今天关于《函数接口的带有命名和非命名参数》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>