只是想知道以下两者之间的区别:
z := make(map[*test] string)
和
z := map[*test] string{}
我是在想象吗,还是它们都无效?
只是想知道以下两者之间的区别:
z := make(map[*test] string)
和
z := map[*test] string{}
我是在想象吗,还是它们都无效?
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 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{}
make()
函数和空map的初始化器是相同的。
使用相同的语法可以用来初始化一个空map,这在功能上与使用
make
函数是相同的:
m = map[string]int{}
来自https://blog.golang.org/go-maps-in-action
将指针用作map键是有效的,因为指针是可比较的。
尽管如此,请记住这些指针指向的值未经检查:
指针值是可比较的。如果两个指针值指向同一变量或者两个值都为nil,那么它们是相等的。指向不同零大小变量的指针可能相等,也可能不相等。
var z map[int]string
和z := map[int]string{}
(等同于z := make(map[int]string)
)之间有什么区别? - Oladapo Ajala