type (
A struct {
a string
}
B struct {
b *A.a
}
)
我收到这个错误:
A.a undefined (type A has no method a)
我是不是漏掉了什么?还是 Go 中不允许这样做?
最佳答案
定义结构字段时,必须指定 its name and its type就像你对 struct A.a
所做的那样。但是在结构 B
中:
b *A.a
*A.a
不是类型。
您不能将 struct
的字段嵌入到另一个结构中。请注意,您可以通过省略 name 部分来将 complete 结构嵌入到另一个结构中,如下所示:
type (
A struct {
a string
}
B struct {
A
}
)
结果是 A
类型的所有字段和方法也将成为结构 B
的成员。如果您需要 B
的嵌入结构 A
,您可以通过引用它作为类型名称来访问它:
var b B
fmt.Println(b.A)
您可以做的另一件事是在 B
中有一个字段,它是一个指针,它指向类型为 A的现有值的字段
:
B struct {
ap *string
}
a := A{a:"test"}
b := B{ap:&a.a} // B.ap will point to a.a
fmt.Println(*b.ap) // Prints "test"
关于go - 使用结构成员作为另一个结构中的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29598131/