在Go语言中查找自定义类型的底层类型。

huangapple go评论136阅读模式
英文:

find underlying type of custom type in golang

问题

你可以使用反射(reflect)包中的TypeOfElem方法来获取item的底层类型。下面是一个示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type M map[string]interface{}
  7. func main() {
  8. var item M
  9. fmt.Println(reflect.TypeOf(item).Elem())
  10. }

这将输出map[string]interface {},即item的底层类型。

英文:
  1. type M map[string]interface{}
  2. var item M
  3. fmt.Println(reflect.TypeOf(item))

returns main.M.

How can I find underlying type of item as map[string]interface{}.

答案1

得分: 3

是的,如果你指的是“根类型”,你可以获取类型的精确结构:

  1. var item M
  2. t := reflect.TypeOf(item)
  3. fmt.Println(t.Kind()) // map
  4. fmt.Println(t.Key()) // string
  5. fmt.Println(t.Elem()) // interface {}

测试一下

从这里开始,你可以按照你的需求进行显示。

英文:

Yes, you can fetch the precise structure of the type, if that's what you mean with "root type":

  1. var item M
  2. t := reflect.TypeOf(item)
  3. fmt.Println(t.Kind()) // map
  4. fmt.Println(t.Key()) // string
  5. fmt.Println(t.Elem()) // interface {}

test it

From there you're free to display it as you want.

答案2

得分: 0

我不认为有一种现成的方法,但你可以手动构建底层类型:

  1. type M map[string]interface{}
  2. ...
  3. var m M
  4. t := reflect.TypeOf(m)
  5. if t.Kind() == reflect.Map {
  6. mapT := reflect.MapOf(t.Key(), t.Elem())
  7. fmt.Println(mapT)
  8. }

你可以通过上述代码手动构建底层类型。

英文:

I don't think there's an out-of-the-box way, but you can construct the underlying type by hand:

  1. type M map[string]interface{}
  2. ...
  3. var m M
  4. t := reflect.TypeOf(m)
  5. if t.Kind() == reflect.Map {
  6. mapT := reflect.MapOf(t.Key(), t.Elem())
  7. fmt.Println(mapT)
  8. }

huangapple
  • 本文由 发表于 2017年8月22日 20:26:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/45817640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定