Interface literals in Go

Issue

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

Solution

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.

Answered By – Adrian

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.