Go:关于结构数组初始化的困惑
Go: Confusion about initialization of struct array
我的困惑如下代码片段所示:
type Ex struct{
A,B int
}
a := []Ex{Ex{1, 2}, Ex{3, 4}} //it works, and I understand it
b := []*Ex{&Ex{1, 2}, &Ex{3, 4}} //it works, and I understand it
c := []Ex{{1, 2}, {3, 4}} //it works, and I don't understand it
d := []*Ex{{1, 2}, {3, 4}} //it works, and I don't understand it
e := []*Ex{{1, 2}, &Ex{3, 4}} //it works, and I don't understand it
最让我疑惑的是c := []Ex{{1, 2}, {3, 4}}
和d := []*Ex{{1, 2}, {3, 4}}
都可以正常工作。为什么{1, 2}
既可以初始化对象又可以初始化指针?
我找到 the same question 并且有人回答:
If is a pointer like *Ex or *Track, it also automatically initializes correctly:
但我希望得到更深入的解释。这个问题有官方文档吗?
本人C/C++基础不错,但是Golang新手。期待您的回答,在此先感谢您。
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
.
这解释了案例 c
、d
以及 e
。
c := []Ex{{1, 2}, {3, 4}}
d := []*Ex{{1, 2}, {3, 4}}
e := []*Ex{{1, 2}, &Ex{3, 4}}
这些都是切片复合字面量,元素也是用复合字面量提供的。所以引用的部分适用。根据规范,您可以从元素的复合文字中省略 T
的元素类型(如果它是指针类型,也可以省略 &
运算符),在这种情况下,它是从切片的元素类型(“外部”复合文字)。
在 c
的情况下,{1, 2}
被解释为复合文字 Ex{1, 2}
。
在d
的情况下,{1, 2}
被解释为&Ex{1, 2}
,即取复合文字Ex{1, 2}
.
的地址
情况e
也是如此(因为切片的元素类型相同)。
这是语言规范允许的复合文字的简化。当从切片类型中知道元素类型时,重复所有元素的元素类型是多余的,会使代码更长且更难阅读。
我的困惑如下代码片段所示:
type Ex struct{
A,B int
}
a := []Ex{Ex{1, 2}, Ex{3, 4}} //it works, and I understand it
b := []*Ex{&Ex{1, 2}, &Ex{3, 4}} //it works, and I understand it
c := []Ex{{1, 2}, {3, 4}} //it works, and I don't understand it
d := []*Ex{{1, 2}, {3, 4}} //it works, and I don't understand it
e := []*Ex{{1, 2}, &Ex{3, 4}} //it works, and I don't understand it
最让我疑惑的是c := []Ex{{1, 2}, {3, 4}}
和d := []*Ex{{1, 2}, {3, 4}}
都可以正常工作。为什么{1, 2}
既可以初始化对象又可以初始化指针?
我找到 the same question 并且有人回答:
If is a pointer like *Ex or *Track, it also automatically initializes correctly:
但我希望得到更深入的解释。这个问题有官方文档吗?
本人C/C++基础不错,但是Golang新手。期待您的回答,在此先感谢您。
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 ofT
. Similarly, elements or keys that are addresses of composite literals may elide the&T
when the element or key type is*T
.
这解释了案例 c
、d
以及 e
。
c := []Ex{{1, 2}, {3, 4}}
d := []*Ex{{1, 2}, {3, 4}}
e := []*Ex{{1, 2}, &Ex{3, 4}}
这些都是切片复合字面量,元素也是用复合字面量提供的。所以引用的部分适用。根据规范,您可以从元素的复合文字中省略 T
的元素类型(如果它是指针类型,也可以省略 &
运算符),在这种情况下,它是从切片的元素类型(“外部”复合文字)。
在 c
的情况下,{1, 2}
被解释为复合文字 Ex{1, 2}
。
在d
的情况下,{1, 2}
被解释为&Ex{1, 2}
,即取复合文字Ex{1, 2}
.
情况e
也是如此(因为切片的元素类型相同)。
这是语言规范允许的复合文字的简化。当从切片类型中知道元素类型时,重复所有元素的元素类型是多余的,会使代码更长且更难阅读。