On Wed, Oct 10, 2018 at 10:04 AM Chris Hopkins <cbehopk...@gmail.com> wrote:
>
> Hi,
> I appreciate this is not possible, but realised I never understood why (so 
> have just been working around it).
> Example code at:
> https://play.golang.org/p/BgFL9T0KiC7
>
> I can create a struct with other structs as a member. I then get all the 
> fields and methods associated with that member.

Technically that's not true.  If you call a method on an embedded
struct field, the method has the embedded field as the receiver, not
the containing struct.

type S struct{}
func (s S) A() {}

type X struct {
  S
}
x:=X{}

Here, x.A() works on x.S, not x. The crucial difference is that this
is composition, not inheritance. The enclosing struct is not a subtype
of the enclosed struct.

One way to look at this is purely syntactical. If you have:

type Y struct {
   s S
}
y:=Y()

To call B(), you have to use the member name: y.s.B(). When the member
has no name, you simply drop the indirection, thus: x.B(), which is,
in fact, the same thing as x.S.B()







> But you can't cast from that master struct back to the member struct.
> i.e. I can create a type T with subtype S and operate on the members and data 
> within S, but can't cast T to S.
> I guessed that when you define type S, it exists as effectively a pointer to 
> a struct, and then members within that struct are an indexed offset from that 
> pointer. The act of creating S within T is simply extending that definition 
> so that T's new fields start where S's finished. Casting back from T should 
> therefore be trivial, but clearly it isn't :-)
>
>
> I'm sure there's a good reason, but it escapes me at the moment. Any ideas?
>
> Thanks
>
> Chris
>
> --
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to