问题
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