Reputation: 3933
In 'A tour of Go' there is such phrase
If the top-level type is just a type name, you can omit it from the elements of the literal.
I'm new in Go so I'm curious when can not it be omitted?
var m = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967}, //top-level type is omitted
"Google": {37.42202, -122.08408},
}
Upvotes: 7
Views: 1132
Reputation: 3933
Also type can be omitted in a map literal when there is an anonymous struct
import (
"fmt"
)
func main() {
var m = map[string]struct{ Lat, Long float64 }{
"Bell Labs": {40.68433, -74.39967},
"Google": {37.42202, -122.08408},
}
fmt.Println(m)
}
Upvotes: 0
Reputation: 156394
As mentioned by commenter @TimCooper, if Vertex
were an interface type then you would need to explicitly name the concrete type which implements the interface since the compiler couldn't reasonably guess which implementation you are referring to, for example:
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{},
}
Upvotes: 6