如何在Go中使用map作为数据载体?

lza*_*zap -1 constructor dictionary types pointers go

我不确定正确的术语,但我如何使用它:

type MyType map[string]string
Run Code Online (Sandbox Code Playgroud)

作为"数据载体"(或OOP中的对象)?

这不起作用:

func NewMyType() *MyType {
    return make(MyType)
}
Run Code Online (Sandbox Code Playgroud)

我确实想使用指针,但显然这不起作用,编译器期望返回时引用.

icz*_*cza 5

内置make()函数创建地图类型的非指针MyType,但返回类型是指针.如果您尝试编译它,那就是错误消息告诉的内容:

不能在返回参数中使用make(MyType)(类型MyType)作为类型*MyType

如果返回指向该值的指针,则它有效:

type MyType map[string]string

func NewMyType() *MyType {
    m := make(MyType)
    return &m
}
Run Code Online (Sandbox Code Playgroud)

如果你想为它使用一行,你可以使用复合文字:

func NewMyType() *MyType {
    return &MyType{}
}
Run Code Online (Sandbox Code Playgroud)

但是地图(地图值)已经在后台实现为指针,因此这是多余的,不必要的.只需按原样返回map-value:

type MyType map[string]string

func NewMyType() MyType {
    return make(MyType)
}
Run Code Online (Sandbox Code Playgroud)

或者使用复合文字:

func NewMyType() MyType {
    return MyType{}
}
Run Code Online (Sandbox Code Playgroud)

虽然这种简单类型(简单创建)的"构造函数"不是必需的,除非你想在返回之前做其他事情(例如,指定其初始容量或用初始值填充它).