dqj29136 2018-06-29 08:13
浏览 76
已采纳

如何将类型传递给函数参数

ERROR: type CustomStruct is not an expression.

type CustomStruct struct {
}

func getTypeName(t interface{}) string {
    rt := reflect.TypeOf(t).Elem()
    return rt.Name()
}

getTypeName(CustomStruct)

How can I pass struct type to function without type instance?

This will work

getTypeName((*CustomStruct)(nil))

But I wonder if there is more simple version..

  • 写回答

1条回答 默认 最新

  • duanguan3863 2018-06-29 08:19
    关注

    You can't. You can only pass a value, and CustomStruct is not a value but a type. Using a type identifier is a compile-time error.

    Usually when a "type" is to be passed, you pass a reflect.Type value which describes the type. This is what you "create" inside your getTypeName(), but then the getTypeName() will have little left to do:

    func getTypeName(t reflect.Type) string {
        return t.Name()
    }
    
    // Calling it:
    getTypeName(reflect.TypeOf(CustomStruct{}))
    

    (Also don't forget that this returns an empty string for anonymous types such as []int.)

    Another way is to pass a "typed" nil pointer value as you did, but again, you can just as well use a typed nil value to create the reflect.Type too, without creating a value of the type in question, like this:

    t := reflect.TypeOf((*CustomStruct)(nil)).Elem()
    fmt.Println(t.Name()) // Prints CustomStruct
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?