简体   繁体   English

如何在父函数中获取子结构名称?

[英]how can i get child struct name in parent func?

how can i get child struct name in parent func?如何在父函数中获取子结构名称? my online code is here: https://go.dev/play/p/04w5mK0aAgL我的在线代码在这里: https://go.dev/play/p/04w5mK0aAgL

type IParent interface {
    TypeName() string
}

type Parent struct{ IParent }

func (p *Parent) TypeName() string {

    if t := reflect.TypeOf(p); t.Kind() == reflect.Ptr {
        return "*" + t.Elem().Name()
    } else {
        return t.Name()
    }
}

type Child struct {
    *Parent
}

func main() {
    var e IParent = &Child{}

    // output: TypeName: *Parent.
    // expected: TypeName: *Child.
    val := e.TypeName()
    fmt.Printf("TypeName: %v.\n", val)
}

the output is TypeName: *Parent. output 是TypeName: *Parent. , my expected output is TypeName: *Child. ,我预期的 output 是TypeName: *Child. , could someone can give me some suggest? ,有人可以给我一些建议吗?

I think u miss with the concept of struct in go.我想你想念 go 中的结构概念。

type Child struct {
    *Parent
}

func main() {
    var e IParent = &Child{}

Above, clearly if u define the struct Child with Parent as the content of struct, but afterthat u declare the child and output the content.上面,很明显,如果你定义了带有 Parent 的 struct Child 作为 struct 的内容,但之后你声明了 child 和 output 的内容。 In here so clearly the result is *Parent.在这里很明显,结果是 *Parent。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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