在“环游世界”中有这样的短语
如果顶级类型只是类型名称,则可以从文字元素中将其忽略。
我是Go语言的新手,所以很好奇何时不能省略它?
var m = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967}, //top-level type is omitted
"Google": {37.42202, -122.08408},
}
Run Code Online (Sandbox Code Playgroud)
正如评论者@TimCooper 所提到的,如果Vertex是接口类型,那么您需要显式命名实现该接口的具体类型,因为编译器无法合理猜测您指的是哪个实现,例如:
type NoiseMaker interface { MakeNoise() string }
type Person struct {}
func (p Person) MakeNoise() string {
return "Hello!"
}
type Car struct {}
func (c Car) MakeNoise() string {
return "Vroom!"
}
// We must provide NoiseMaker instances here, since
// there is no implicit way to make a NoiseMaker...
noisemakers := map[string]NoiseMaker{
"alice": Person{},
"honda": Car{},
}
Run Code Online (Sandbox Code Playgroud)