donglun7151 2016-11-30 03:28
浏览 128
已采纳

Golang反映:从名称获取类型表示形式?

Is there a way to use the reflection libraries in Go to go from the name of a type to its Type representation?

I've got a library where the user needs to provide Type representations for some code generation. I know it must be possible (in a sense) because they can just create a variable of that type and call the TypeOf function, but is there a way to circumvent this and just get representation from the name?

  • 写回答

1条回答 默认 最新

  • dsgoj7457 2016-11-30 07:52
    关注

    The question is not quite explicit, it can be interpreted in 2 ways, to one of which the answer is no, not possible; and the other to which the answer is yes, it's possible.

    At runtime

    If the type name is provided as a string value, then at runtime it's not possible as types that are not referred to explicitly may not get compiled into the final executable binary (and thus obviously become unreachable, "unknown" at runtime). For details see Splitting client/server code. For possible workarounds see Call all functions with special prefix or suffix in Golang.

    At "coding" time

    If we're talking about "coding" time (source code writing / generating), then it's possible without creating / allocating a variable of the given type and calling reflect.TypeOf() and passing the variable.

    You may start from the pointer to the type, and use a typed nil pointer value without allocation, and you can navigate from its reflect.Type descriptor to the descriptor of the base type (or element type) of the pointer using Type.Elem().

    This is how it looks like:

    t := reflect.TypeOf((*YourType)(nil)).Elem()
    

    The type descriptor t above will be identical to t2 below:

    var x YourType
    t2 := reflect.TypeOf(x)
    
    fmt.Println(t, t2)
    fmt.Println(t == t2)
    

    Output of the above application (try it on the Go Playground):

    main.YourType main.YourType
    true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制