Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can be used in a map literal instead of a type name in Go?

Tags:

go

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},
}
like image 503
Daniil Grankin Avatar asked Nov 30 '17 17:11

Daniil Grankin


1 Answers

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{},
}
like image 142
maerics Avatar answered Oct 23 '22 04:10

maerics