英文:
Can I use a pointer to a nested struct as a receiver parameter?
问题
通过使用x *A
作为接收器,我可以将B引用为x.B
。
但是,我希望将与B嵌套结构相关的方法保持在它们自己的“命名空间”中,通过使用与父结构的方法不同的接收器。(并避免函数名称冲突)
type A struct {
//...
B struct {
// ...
}
}
//...
func (x *A.B) method() {
}
错误:A.B未定义(类型A没有B方法)编译器(MissingFieldOrMethod)
英文:
By using x *A
as a receiver I could reference B as x.B
But I'd like to keep methods related to the B nested struct in their own namespace (if you will) by having a different receiver than the methods of the parent struct. (And avoiding func name clashes)
type A struct {
//...
B struct {
// ...
}
}
//...
func (x *A.B) method() {
}
Error: A.B undefined (type A has no method B) compiler(MissingFieldOrMethod)
答案1
得分: 2
我刚刚发现我必须在结构体A之外定义B的类型,并直接在接收器中引用B。
在我的第一个例子中,B是A的一个未命名类型的属性,当然对于接收器参数,你必须引用一个命名类型。
(或者有没有一种方法可以从实例引用一个未命名的结构体?)
修正后的代码:
type A struct {
//...
b B
}
type B struct {
}
//...
func (x *B) method() {
}
//...
a := &A{}
a.b.method()
英文:
I just figured out I have to define B's type outside struct A and reference B directly in the receiver.
In my first example, B is an attribute of A of an unnamed type, and of course for a receiver parameter you have to reference a named type.
(Or is there a way to reference an unnamed struct from its instance?)
Corrected code:
type A struct {
//...
b B
}
type B struct {
}
}
//...
func (x *B) method() {
}
//...
a A = &A{}
a.b.method()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论