Can't use range on slice made with reflect then passed json.Unmarshal

て烟熏妆下的殇ゞ 提交于 2020-07-08 02:31:17

问题


I am getting the following errors from the code below:

invalid indirect of typedSlice (type interface {})

cannot range over typedSlice (type interface {})

This is confusing to me because reflect.TypeOf(copy) matches the type of t.

func Unmarshal(t reflect.Type) []interface{} {

    ret := []interface{}{}
    s := `[{"Name":"The quick..."}]`

    slice := reflect.Zero(reflect.SliceOf(t))
    o := reflect.New(slice.Type())
    o.Elem().Set(slice)
    typedSlice := o.Interface()

    json.Unmarshal([]byte(s), typedSlice)

    fmt.Println(typedSlice)                 // &[{The quick...}]
    fmt.Println(reflect.TypeOf(typedSlice)) //same type as t
    fmt.Println(*typedSlice)                // invalid indirect of copy (type interface {})

    for _, l := range typedSlice {          //cannot range over copy (type interface {})
        ret = append(ret, &l)
    }

    return ret
}

I've created a go playground with working code to help.

Why does it appear that this slice prints one type but compiles as another?


回答1:


invalid indirect of typedSlice (type interface {})

You can't dereference typedSlice, because it's an interface{}. You would have to extract the pointer with a type assertion

realSlice := *typedSlice.(*[]Demo)

cannot range over typedSlice (type interface {})

Again, since typedSlice is an interface{}, you can't range over it. If you want to range over the values you need to use a type assertion, or iterate manually via reflect:

for i := 0; i < o.Elem().Len(); i++ {
    ret = append(ret, o.Elem().Index(i).Interface())
}


来源:https://stackoverflow.com/questions/34163174/cant-use-range-on-slice-made-with-reflect-then-passed-json-unmarshal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!