反射切片的底层类型

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

Reflect slice underlying type

问题

我有以下代码:

v := &[]interface{}{client, &client.Id}
valType := reflect.TypeOf(v)
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
    elm := val.Elem()
    if elm.Kind() == reflect.Slice {
        fmt.Println("Type ->>", elm, " - ", valType.Elem())
    }
}

输出结果如下:Type ->> <[]interface {} Value> - []interface {}
我该如何获取它的底层类型?我想检查数组类型是否为interface{}类型。

编辑
一种实现方式,我认为不太好看的方式是:

var t []interface{}
fmt.Println("Type ->>", elm, " - ", valType.Elem(), " --- ", reflect.TypeOf(t) == valType.Elem())

有没有其他方法可以实现?

英文:

I have the following code:

v: = &amp;[]interface{}{client, &amp;client.Id}
valType := reflect.TypeOf(v)
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
		elm := val.Elem()
		if elm.Kind() == reflect.Slice {
			fmt.Println(&quot;Type -&gt;&gt;&quot;, elm, &quot; - &quot;, valType.Elem())
		}
	}

The output is the following one: Type -&gt;&gt; &lt;[]interface {} Value&gt; - []interface {}
How can I get the underlying type of it? I would like to check if array type is of interface{} kind.

EDIT
One way to achieve it, an ugly way IMHO is this one:

var t []interface{}
fmt.Println(&quot;Type -&gt;&gt;&quot;, elm, &quot; - &quot;, valType.Elem(), &quot; --- &quot;, reflect.TypeOf(t) == valType.Elem())

Can it be done in a different way?

答案1

得分: 3

假设我们有 v := make([]Foo, 0)。如何获取 Foo 类型而不是 []Foo

正如你已经发现的那样,在你使用切片指针的情况下,valType.Elem().Elem() 可以工作。

但对于普通切片,就像在 "golang reflect value kind of slice" 中所述,只需要这样做:

typ := reflect.TypeOf(<var>).Elem()
英文:

> Let us assume the we have v := make([]Foo, 0).
How to get the Foo type and not []Foo?

As you have found out, valType.Elem().Elem() can work, in your case where you are using a slice pointer.

But for a regular slice, as in "golang reflect value kind of slice", this would be enough:

typ := reflect.TypeOf(&lt;var&gt;).Elem()

huangapple
  • 本文由 发表于 2014年6月23日 21:13:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/24366895.html
匿名

发表评论

匿名网友

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

确定