【问题标题】:Can someone explain this result?有人可以解释这个结果吗?
【发布时间】:2021-01-06 18:11:56
【问题描述】:

有一个关于go反射的demo:

func main() {
        test := []string{"hello"}
        V := reflect.ValueOf(test)
        if reflect.TypeOf(V).Kind() == reflect.Struct{
            fmt.Printf("it's a struct")
        } else {
            fmt.Printf("other")
        }
    }

输出是"it's a struct"

【问题讨论】:

    标签: go struct reflection slice


    【解决方案1】:

    Vreflect.ValueOf()返回的值,所以它的类型是reflect.Value,是一个struct,所以reflect.TypeOf(V).Kind()就是reflect.Struct。没有什么令人惊讶的。

    来自reflect 包:

    type Value struct {
        // contains filtered or unexported fields
    }
    

    如果你传递test 本身,它的种类将是reflect.Slice

    if reflect.TypeOf(test).Kind() == reflect.Slice {
        fmt.Printf("it's a slice")
    } else {
        fmt.Printf("other")
    }
    

    这将打印(在Go Playground 上尝试):

    it's a slice
    

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2013-01-09
      • 2012-04-19
      • 1970-01-01
      • 2010-11-27
      相关资源
      最近更新 更多