简体   繁体   中英

How to get child's type in golang

I've been studying Go recently. In the under sample, I got the type a, not b. Why? And how do I get b?

// parent
type A struct {
    foo string
}

func (a *A) say() {
    // I want b here, not a
    fmt.Println(reflect.ValueOf(a).Type().String())
}

// child
type B struct {
    A
}

func main() {
    b := new(B)
    b.say()
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM