我很惊讶我可以用这种方式初始化一片指针:
package main
import (
"fmt"
)
type index struct {
i, j int
}
func main() {
indices := []*index{{0, 1}, {1, 3}} // Why does this work?
fmt.Println(*indices[1])
}
我原以为必须写一些更冗长的东西,比如:
indices := []*index{&index{0, 1}, &index{1, 3}}
我可以在文档的什么地方找到它?
最佳答案
来自 the spec :
Within a composite literal of array, slice, or map type T, elements or map keys that are themselves composite literals may elide the respective literal type if it is identical to the element or key type of T. Similarly, elements or keys that are addresses of composite literals may elide the &T when the element or key type is *T.
基本上,它已经知道每个元素都是一个 *index
,因此您不必一遍又一遍地实际键入 &index
。
如果 slice 类型与元素类型不同(可能是接口(interface)类型的 slice ),您必须像这样指定每个元素的类型:
索引 := []interface{}{&index{0, 1}, &index{1, 3}}
关于go - 我怎么能像这样初始化一片指针呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229931/