【问题标题】:Reference type of expression with Golang用 Golang 引用表达式的类型
【发布时间】:2018-12-02 23:55:27
【问题描述】:

我有这个

var Map = map[string]Model{}

var (
    mtx    sync.Mutex
    people Map
)

我收到此错误:

有没有办法引用 Map 的类型,像这样:

var (
    mtx    sync.Mutex
    people reflect.Type(Map)  // <<< ?
)

或者我应该像这样声明类型:

type Map map[string]Model

像我在第 54 行那样初始化地图?我只是想在文件中初始化地图,而不必在 Init func 中进行。

【问题讨论】:

  • 您使用Map 的方式是作为一种类型,所以是的,您应该将它声明为一种类型。在声明变量时,您不能使用 reflect 获取要使用的其他对象的类型(尽管如果您在声明中将新变量分配给该其他对象,它将属于同一类型)。

标签: go


【解决方案1】:

我想你想使用类似的东西

type Model struct{}
type ModelMap map[string]Model

var (
    mtx sync.Mutex
    people = ModelMap{}
)

【讨论】:

    【解决方案2】:

    您可以使用地图文字来初始化地图:

    type Model struct {}
    
    var people = map[string]Model{
        "Foo": Model{},
        "Bar":   Model{},
    }
    

    【讨论】:

      【解决方案3】:

      我不确定我是否理解您的问题,但您可以这样做:

       var Map = map[string]Model{}
      
       var (
         mtx sync.Mutex
         people = Map
       )
      

      这样people的初始化就和Map一样。

      【讨论】:

        猜你喜欢
        • 2019-03-13
        • 1970-01-01
        • 2022-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        相关资源
        最近更新 更多