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).

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

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择