mardi 5 septembre 2017

golang refect interface{} to []interface{} and change array value

I have the following codes:

func f(data interface{}) interface{} {
    switch data.(type) {
    case int:
        return 0
    case []interface{}:
        ref_data := reflect.ValueOf(data)
        for i := 0; i < ref_data.Len(); i++ {
            fmt.Println(ref_data.Index(i))
        }
        return 0
    }
    return 0
}
func main() {
    a := []int{1, 2, 3, 4}
    f(a)
    fmt.Println("******")
    fmt.Println(a)
}

Issue 1: in line []interface{}, it doesn't work, just []int works, but in the real case, it may be []string, []float64 and so on. so I don't want to case []string, []int, []float64 and so on, could I make the []interface{} work here?

Issue 2: during integrate ref_data, I do want to change the data. like ref_data[idx] = f(ref_data.Index(i).Interface()) however the ref_data[idx] doesn't work here all, any suggestion?





Aucun commentaire:

Enregistrer un commentaire