-1

考虑以下代码:

package main

import (
    "fmt"
    "reflect"
)

func f(v interface{}) {
    fmt.Println(reflect.TypeOf(v).Elem())
    fmt.Println(reflect.ValueOf(v))
}
func main() {
    var aux []interface{}
    aux = make([]interface{}, 2)
    aux[0] = "foo"
    aux[1] = "bar"
    f(aux)
}

输出是:

interface {}
[foo bar]

如何确定 interface{} 切片中包含的元素的类型,在这个特定示例中,我需要在我的函数中知道f该 interface{} 切片包含string值。

我的用例是,使用反射,我试图根据我的 interface{} 参数切片所持有的值的类型来设置一个结构字段。

4

1 回答 1

1

你传入的值是 type []interface{},所以元素类型是interface{}. 如果您想查看元素类型是什么,则需要单独思考:

func f(i interface{}) {
    v := reflect.ValueOf(i)
    for i := 0; i < v.Len(); i++ {
        e := v.Index(i)
        fmt.Println(e.Elem().Type())
        fmt.Println(e)
    }
}

如果您知道您将始终拥有一个[]interface{},请将其用作参数类型以使迭代和类型检查更容易:

func f(things []interface{}) {
    for _, thing := range things {
        v := reflect.ValueOf(thing)
        fmt.Println(v.Type())
        fmt.Println(v)
    }
}
于 2020-03-13T19:56:24.673 回答