You got always the A value because you have only one say()
method which point to A struct.
So, when you apply the say()
method to B struct, the compiler will look at B struct and its fileds in order to find if there is a say()
method of B struct or there is any field of B struct who have a say()
method.
In your case, B struct doesn't have any method which will point to it. But it have a field which cointain A struct and which have a say()
method.
So, everytime you'll call the say()
method within B struct, you'll call B.A.say()
which will print the A value.
Otherwise, if you want to print B and A values, you can modify your code to something like this example:
package main
import (
"fmt"
"reflect"
)
type A struct {
foo string
}
// This method will point to A struct
func (a *A) say() {
fmt.Println(reflect.ValueOf(a).Type().String())
}
type B struct {
A
}
// This method will point to B struct
func (a *B) say() {
fmt.Println(reflect.ValueOf(a).Type().String())
}
func main() {
b := new(B)
b.say() // expected output: *main.B
b.A.say() // expected output: *main.A
}
Output:
*main.B
*main.A
You can also run this code with Go Playground