本文介绍了无法在通过反射然后传递的json制成的切片上使用范围.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从下面的代码中收到以下错误:

I am getting the following errors from the code below:

不能超出typedSlice(类型接口{})的范围

cannot range over typedSlice (type interface {})

这使我感到困惑,因为 reflect.TypeOf(copy) t 的类型匹配.

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?

推荐答案

您不能取消引用 typedSlice ,因为它是接口{} .您将必须使用类型断言来提取指针

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

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

同样,由于 typedSlice 是一个 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())
}

这篇关于无法在通过反射然后传递的json制成的切片上使用范围.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:58