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 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计