【问题标题】:golang reflect value kind of slicegolang 反映值类型的切片
【发布时间】:2019-06-06 19:49:03
【问题描述】:
fmt.Println(v.Kind())
fmt.Println(reflect.TypeOf(v))

如何知道切片反射值的类型?

以上结果

v.Kind = slice
typeof = reflect.Value

当我尝试Set 时,如果我创建了错误的切片,它将崩溃

t := reflect.TypeOf([]int{})
s := reflect.MakeSlice(t, 0, 0)
v.Set(s)

例如 []int{} 而不是 []string{} 所以我需要在创建反射值之前知道确切的切片类型。

【问题讨论】:

    标签: go


    【解决方案1】:

    首先,我们需要通过测试确保我们正在处理一个切片:reflect.TypeOf(<var>).Kind() == reflect.Slice

    如果没有该检查,您将面临运行时恐慌的风险。所以,现在我们知道我们正在使用切片,查找元素类型就像:typ := reflect.TypeOf(<var>).Elem()

    由于我们可能期望许多不同的元素类型,我们可以使用 switch 语句来区分:

    t := reflect.TypeOf(<var>)
    if t.Kind() != reflect.Slice {
        // handle non-slice vars
    }
    switch t.Elem().Kind() {  // type of the slice element
        case reflect.Int:
            // Handle int case
        case reflect.String:
            // Handle string case
        ...
        default:
            // custom types or structs must be explicitly typed
            // using calls to reflect.TypeOf on the defined type.
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-13
      • 2013-10-23
      • 2016-05-25
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 2017-10-28
      相关资源
      最近更新 更多