如何使用双指针字段初始化结构?我试图初始化一个结构如下:
type atype struct {
val string
}
a := &struct {
StringValue string
Pointer **atype
}{
StringValue: "FOO",
//this is the relevant bit
Pointer : &(&atype{
val: "test"
})
}
invalid pointer type **basicAppConfig for composite literal
我的逻辑有什么问题?我把指针指向一个指向值的指针.
我也试过用
reflect.PtrTo(&atype{
val: "string"
})
没有成功...
1> Kaedys..:
除非分配给变量,否则指针不可寻址.获取复合文字的地址而不将其分配给变量的能力仅限于结构,数组,切片和映射.
要执行您想要执行的操作,必须先将指针指定给变量,然后在结构文字中指定该(指针)变量的地址:
https://play.golang.org/p/7WyS732H3cZ
package main
type atype struct {
val string
}
func main() {
at := &atype{
val: "test",
}
a := &struct {
StringValue string
Pointer **atype
}{
StringValue: "FOO",
Pointer: &at,
}
_ = a
}
参考文献:
https://golang.org/ref/spec#Address_operators
https://golang.org/ref/spec#Composite_literals