如何写一个可以得到任何结构并返回结构名的函数?

问题描述 投票:-1回答:1

我试着写了一个这样的函数。

func getStuctName(aStruct interface{}) string {
    typeof := reflect.TypeOf(aStruct)

    if typeof.Kind() == reflect.Ptr {
         typeof = typeof.Elem()
    }

    return typeof.Name()
}

但结果是空白的 ""

当我用一个结构的指针来调用我的函数时,我尝试了这样的函数:func getStuctName(aStruct interface{} string { typeof := reflect.TypeOf(aStruct) if typeof.Kind(== reflect.P.Sty())。

func callerFunction(aStruct interface{})  {
    fmt.Println(getStructName(&aStruct))
}
go reflection
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.