make(map)和map{}之间的区别

34

只是想知道以下两者之间的区别:

z := make(map[*test] string)

z := map[*test] string{}

我是在想象吗,还是它们都无效?

2个回答

33

The Go Programming Language Specification

Making slices, maps and channels

The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values.

Call         Type T  Result
make(T)      map     map of type T
make(T, n)   map     map of type T with initial space for approximately n elements

Composite literals

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.

map[string]int{}
map[string]int{"one": 1}

make 是规范的形式。复合字面量是一个方便且替代的形式。

z := make(map[int]string)

并且

z := map[int]string{}

它们是等价的。

简洁回答。那么 var z map[int]stringz := map[int]string{}(等同于 z := make(map[int]string))之间有什么区别? - Oladapo Ajala
2
据我所知,有一点不同。代码 var z map[int]string 会生成 nil,而另外两个代码 z := make(map[int]string) 和 z := map[int]string{} 会生成一个空切片。这三个可以在 range 循环等中使用,但如果需要的话,仍然可以检测它们之间的差异。 - Norman

12

make()函数和空map的初始化器是相同的。

使用相同的语法可以用来初始化一个空map,这在功能上与使用make函数是相同的:

m = map[string]int{}

来自https://blog.golang.org/go-maps-in-action

将指针用作map键是有效的,因为指针是可比较的

尽管如此,请记住这些指针指向的值未经检查:

指针值是可比较的。如果两个指针值指向同一变量或者两个值都为nil,那么它们是相等的。指向不同零大小变量的指针可能相等,也可能不相等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接