亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

與具有命名參數和未命名參數的函數的接口

與具有命名參數和未命名參數的函數的接口

Go
眼眸繁星 2022-07-25 10:17:45
我正在學習 Go 中的 protobuf 和 gRPC。在生成 pb.go 文件時protoc --go_out=plugins=grpc:chat chat.proto對于文件chat.protosyntax = "proto3";package chat;message Message {  string body = 1;}service ChatService {  rpc SayHello(Message) returns (Message) {}}生成的chat.pb.go有這兩個接口:type ChatServiceClient interface {    SayHello(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)}...type ChatServiceServer interface {    SayHello(context.Context, *Message) (*Message, error)}ChatServiceClient我對在界面中使用命名參數感到困惑。有沒有使用這些參數ctx:in和opts。在這種情況下,我們什么時候應該命名參數和未命名參數?
查看完整描述

1 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

參數名稱是可選的,在接口的情況下,它可以純粹用于文檔目的。


規格:接口:


InterfaceType      = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" .

MethodSpec         = MethodName Signature .

方法簽名在哪里:


Signature      = Parameters [ Result ] .

Result         = Parameters | Type .

Parameters     = "(" [ ParameterList [ "," ] ] ")" .

ParameterList  = ParameterDecl { "," ParameterDecl } .

ParameterDecl  = [ IdentifierList ] [ "..." ] Type .

如您所見,IdentifierListinParameterDecl在方括號中,這意味著它是可選的。


想一個這樣的例子:


type FileMover interface {

    MoveFile(dst, src string) error

}

它“響亮而清晰”。如果我們省略參數名稱怎么辦?


type FileMover interface {

    MoveFile(string, string) error

}

第一個參數是否標識源或目標并不明顯。提供dst和src命名文件,它使 thar 清楚。


當你實現一個接口并為一個方法提供實現時,如果你想引用參數,你必須命名它們,因為你用它們的名字來引用它們,但是如果你不想引用參數, 即使這樣它們也可能被省略。


查看完整回答
反對 回復 2022-07-25
  • 1 回答
  • 0 關注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號