dpda53918 2016-12-14 06:17
浏览 33
已采纳

如何在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()
}
  • 写回答

1条回答 默认 最新

  • douguangxiang0363 2016-12-14 07:13
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?