gopointersreceiver

Can I use a pointer to a nested struct as a receiver parameter?


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)


Solution

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