2017-05-26 24 views
0
fmt.Println(v.Kind()) 
fmt.Println(reflect.TypeOf(v)) 

如何找出片的反射值的類型?golang反射值片的種類

v.Kind = slice 
typeof = reflect.Value 

當我嘗試Set如果我創建了錯誤的切片

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

例如[]int{},而不是[]string{}就會死機上述結果,所以我需要知道確切的片在創建之前,反射值的類型。

回答

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() { // 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. 
}