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

There’s such a phrase in Go Tour

If the top level type is just the type name, you can omit it from literal elements.

I'm new to Go, so I wonder when you can't omit it?

var m = map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967},    //top-level type is omitted
    "Google":    {37.42202, -122.08408},
}
+4
source share
2 answers

As @TimCooper commentator mentioned, if it Vertexwas an interface type, you would have to explicitly specify the specific type that implements the interface, since the compiler could not reasonably guess which implementation you are accessing, 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{},
}
+4
source

Also, a type can be omitted literally when there is an anonymous structure.

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)
}
0
source

Source: https://habr.com/ru/post/1690082/


All Articles