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

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

find underlying type of custom type in golang

问题

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

package main

import (
	"fmt"
	"reflect"
)

type M map[string]interface{}

func main() {
	var item M
	fmt.Println(reflect.TypeOf(item).Elem())
}

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

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

returns main.M.

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

答案1

得分: 3

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

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

测试一下

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

英文:

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

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

test it

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

答案2

得分: 0

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

type M map[string]interface{}
...
var m M
t := reflect.TypeOf(m)
if t.Kind() == reflect.Map {
    mapT := reflect.MapOf(t.Key(), t.Elem())
    fmt.Println(mapT)
}

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

英文:

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

type M map[string]interface{}
...
var m M
t := reflect.TypeOf(m)
if t.Kind() == reflect.Map {
    mapT := reflect.MapOf(t.Key(), t.Elem())
    fmt.Println(mapT)
}

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:

确定