我可以使用指向嵌套结构的指针作为接收器参数吗?

huangapple go评论80阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2021年8月1日 11:23:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/68607298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定