Go语言中的接口字面量

huangapple go评论85阅读模式
英文:

Interface literals in Go

问题

首先澄清一下标题,我知道Go语言中没有接口字面量这样的东西,但我想不出其他名称来描述这个问题。

我在阅读一些Go代码时发现了一个奇怪的结构,如下所示:

clientOptions := []grpc.DialOption{grpc.WithInsecure()}
cc, err := grpc.Dial(l.Addr().String(), clientOptions...)

这里的grpc.DialOption是一个接口类型,grpc.WithInsecure()返回的就是这个类型。引起我的注意的是clientOptions是一个切片,这对我来说似乎是多余的。所以我尝试去掉大括号,像这样:

clientOptions := grpc.DialOption{grpc.WithInsecure()}

但是我得到了编译错误:"invalid composite literal type grpc.DialOption"

我在Go Playground上尝试模拟这个问题,结果得到了相同的错误。
这段代码可以正常运行:
https://go.dev/play/p/QJQR9BDGN4a

但是这个版本在编译时失败,出现了相同的"invalid composite literal type"错误:
https://go.dev/play/p/A0FasDybUg5

有人能解释一下这是为什么吗?
谢谢。

英文:

First to clarify the title, I know there is no such thing as interface literals in Go but I couldn't come up with another name for this issue.

I was reading some Go code and found a weird construct, like so:

clientOptions := []grpc.DialOption{grpc.WithInsecure()}
cc, err := grpc.Dial(l.Addr().String(), clientOptions...)

Here grpc.DialOptions is an interface type and grpc.WithInsecure() returns that type. What caught my eye here is that clientOptions is a slice, which seemed redundant to me. So I tried to remove the braces like so:

clientOptions := grpc.DialOption{grpc.WithInsecure()}

But I get compilation error: "invalid composite literal type grpc.DialOption"

I tried to simulate this on the go playground and I get the same result.
This code runs fine:
https://go.dev/play/p/QJQR9BDGN4a

But this version fails with the same "invalid composite literal type error":
https://go.dev/play/p/A0FasDybUg5

Can someone explain this?
Thanks

答案1

得分: 0

你是正确的,这创建了一个切片:

clientOptions := []grpc.DialOption{grpc.WithInsecure()}

但是我认为你误解了哪个语法做了什么。这将是一个空的切片字面量:

clientOptions := []grpc.DialOption{}

这将是一个单个值,不在切片中:

clientOptions := grpc.WithInsecure()

供参考,这种语法在《Go之旅》中有介绍(https://tour.golang.org/)。

英文:

You are correct that this creates a slice:

clientOptions := []grpc.DialOption{grpc.WithInsecure()}

But I think you've misunderstood which syntax does what. This would be an empty slice literal:

clientOptions := []grpc.DialOption{}

This would be a single value, not in a slice:

clientOptions := grpc.WithInsecure()

For reference, this syntax is covered in the Tour of Go.

huangapple
  • 本文由 发表于 2022年2月19日 05:30:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/71180062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定