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

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

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..

图片转代码服务由CSDN问答提供 功能建议

错误:类型CustomStruct不是表达式。

  type  CustomStruct struct {
} 
 
func getTypeName(t interface {})字符串{
 rt:= reflect.TypeOf(t).Elem()
返回rt.Name()
} 
 
getTypeName(  CustomStruct)
   
 
 

如何在没有类型实例的情况下将结构类型传递给函数?

这将起作用 \ n

  getTypeName((* CustomStruct)(nil))
   
 
 

但是我不知道是否有更简单的版本。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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
    
    点赞 评论

相关推荐 更多相似问题