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

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

报告相同问题?

悬赏问题

  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥15 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环
  • ¥15 ADS已经下载好了,但是DAS下载不了,一直显示这两种情况,有什么办法吗,非常急!
  • ¥100 Excel 点击发送自动跳转outlook邮件
  • ¥15 gis中用栅格计算器或加权总和后图层不显示,值也明显不对
  • ¥15 python使用python-pptx如何给幻灯片添加只读密码。