dongliang7545 2017-11-30 17:13
浏览 16
已采纳

可以在地图文字中代替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},
}
  • 写回答

2条回答 默认 最新

  • dongshang1979 2017-11-30 17:50
    关注

    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{},
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作