简体   繁体   中英

Data type suddenly changes

I am trying to append values to an array. Code as shown below:

func MakeParamFrom(data ...interface{}) (res []interface{}) {
    new := []interface{}{}
    params = &new
    for _, datum := range data {
        processParam(datum)
        fmt.Println("RESULT: ", *params)
    }
    fmt.Println("FINAL: ", *params)
    return *params
}

func processParam(data interface{}) {
    fmt.Println("DATA ", data)
    dataValue := reflect.ValueOf(data)
    fmt.Println("KIND: ", dataValue.Kind())
    dataKind := dataValue.Kind()
    if dataKind == reflect.Array || dataKind == reflect.Slice {
        length := dataValue.Len()
        for i := 0; i < length; i++ {
            fmt.Println(dataValue.Index(i), " is ", dataValue.Index(i).Kind())
            processParam(dataValue.Index(i))
        }
    } else if dataKind == reflect.Struct {
        fieldCount := dataValue.NumField()
        fmt.Println("FIELDCOUNT :", fieldCount)
        for i := 0; i < fieldCount; i++ {
            processParam(dataValue.Field(i).Interface())
        }
    } else {
        *params = append(*params, data)
    }
}

When I test the following:

func TestMakeParamFrom(t *testing.T) {
    data1 := "show"
    data2 := 123
    data3 := []int{1234, 456, 789}
    data4 := someStruct{1, "2"}
    data5 := [2]someStruct{{12, "24"}, {36, "48"}}
    actualOutput := MakeParamFrom(data1, data2, data3, data4, data5)
    expectedOutput := []interface{}{"show", 123, 123, 456, 789, 1, "2", 12, "24", 36, "48"}
    assert.Equal(t, actualOutput, expectedOutput)
}

I got the following result:

DATA  show
KIND:  string
RESULT:  [show]
DATA  123
KIND:  int
RESULT:  [show 123]
DATA  [1234 456 789]
KIND:  slice
1234  is  int
DATA  1234
KIND:  struct
FIELDCOUNT : 3

Why does 1234 change from int to struct? And what should I do if I want 1234 as int (or other types it is supposed to have)? Thanks

I solved this.

The key is to pass the argument as an interface:

if dataKind == reflect.Array || dataKind == reflect.Slice {
        length := dataValue.Len()
        for i := 0; i < length; i++ {
            fmt.Println(dataValue.Index(i), " is ", dataValue.Index(i).Kind())
            processParam(dataValue.Index(i).Interface())
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM