1
  struct A {}

  func (a *A) BName(id int) string {
     return a.Name
  }

  struct B {
     *A
     Name string
  }

  func main() {
     b := &B{Name: "abc"}
     fmt.Println(b.Name)
  }

the code failure, I want know how to write code to achieve, A.BName can access B struct attribute Name

Dave Cheney
  • 5,575
  • 2
  • 18
  • 24
jame2981
  • 51
  • 1
  • 6

2 Answers2

6

This is not possible. struct A does not know anything about the types it is embedded into. Think about it, A can be embedded into any other struct, so how could you know ahead of time the type of the struct that A is embedded into.

If you want to do this, you need to place a reference to B, the outer structure into A.

type A struct {
    *B 
}

func (a *A) PrintName() string { return a.B.Name }

type B struct {
    A // no need to use a pointer here
    Name string
}

var b B
b.A.B = &b

fmt.Println(b.PrintName())
Dave Cheney
  • 5,575
  • 2
  • 18
  • 24
1

A accessing B reminds me of a is-a relationship, where A "is-a" B.

The article "Is Go an Object Oriented language?" does note that there is no true subtyping in Go:

  • if it was truly subtyping then the anonymous field would cause the outer type to become the inner type. In Go this is simply not the case. The two types remain distinct.
  • The anonymous fields are still accessible as if they were embedded

Example:

package main

type A struct{
    // doesn't know anything about B
}

type B struct {
    A  //B is-a A
}

func (a *A) f() { fmt.Println("A.f") }
func (b *B) f() { fmt.Println("B.f") }

func save(A) {
    //do something
}

func main() {
    b := B
    save(&b)  //OOOPS! b IS NOT A
    b.f()     // B.f()
    b.A.f()   // A.f()
}

One of the issues with multiple inheritance is that languages are often non obvious and sometimes even ambiguous as to which methods are used when identical methods exist on more than one parent class.

With Go you can always access the individual methods through a property which has the same name as the type.

In reality when you are using Anonymous fields, Go is creating an accessor with the same name as your type.

That is what "b.A" is: an accessor to an anonymous field..

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250