doxn43207 2018-05-15 10:55
浏览 29
已采纳

如何在Go中将地图用作数据载体?

I am unsure about correct terms, but how do I use this:

type MyType map[string]string

as "data carrier" (or object in OOP)?

This does not work:

func NewMyType() *MyType {
    return make(MyType)
}

I do want to use pointer but apparently this does not work, the compiler expects reference on return.

  • 写回答

1条回答 默认 最新

  • donglian5309 2018-05-15 10:59
    关注

    The builtin make() function creates a non-pointer value of your MyType map type, yet the return type is a pointer. That's what the error message tells if you try to compile it:

    cannot use make(MyType) (type MyType) as type *MyType in return argument

    If you return a pointer to the value, it works:

    type MyType map[string]string
    
    func NewMyType() *MyType {
        m := make(MyType)
        return &m
    }
    

    If you would want to use a single line for it, you could use a composite literal:

    func NewMyType() *MyType {
        return &MyType{}
    }
    

    But maps (map values) are already implement as pointers in the background, so this is redundant and unnecessary. Just return the map-value as-is:

    type MyType map[string]string
    
    func NewMyType() MyType {
        return make(MyType)
    }
    

    Or with a composite literal:

    func NewMyType() MyType {
        return MyType{}
    }
    

    Although "constructors" for such simple types (simple creation) are not necessary, unless you want to do other things before returning it (e.g. specify its initial capacity or fill it with initial values).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含