reflect.Set slice-of-structs值到一个结构,没有类型断言(因为它是未知的)

时间:2016-11-07 21:10:14

标签: go reflection

我正在创建一个帮助程序包来从队列中弹出有效负载。这个帮助程序必须与导入它的应用程序使用的结构无关。

此(无操作,仅示例)函数将从提供的类型like interface{}的队列中提供单个有效负载:

func One(like interface{}) interface{} {
    typ := reflect.TypeOf(like)
    one := reflect.New(typ)

    return one.Interface()
}

此功能提供许多有效负载:

func Many(num int, like interface{}) interface{} {
    typ := reflect.TypeOf(like)
    many := reflect.MakeSlice(reflect.SliceOf(typ), num, num)

    for i := 0; i < num; i++ {
        one := One(typ)
        many.Index(i).Set(one)
    }

    return many.Interface()
}

使用的一个例子是:

type Payload struct {
    Id int
    Text string
}

func main() {
    Many(4, Payload{})
}

但是,上述结果如下:

panic: reflect.Set: value of type **reflect.rtype is not assignable to type main.Payload

https://play.golang.org/p/ud23ZlD3Bx

1 个答案:

答案 0 :(得分:3)

您在reflect.TypeOf上呼叫reflect.Value**reflect.rtype来自One

直接使用like值调用func One(like interface{}) interface{} { typ := reflect.TypeOf(like) one := reflect.New(typ) return one.Interface() } func Many(num int, like interface{}) interface{} { typ := reflect.TypeOf(like) many := reflect.MakeSlice(reflect.SliceOf(typ), num, num) for i := 0; i < num; i++ { one := One(like) many.Index(i).Set(reflect.ValueOf(one).Elem()) } return many.Interface() } 函数,并将该结果分配给切片。

 mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view,
                int position, long id) {

            User user = adapter.getItem(position);
            // Here you can do the action you want to...
          //BUT I DONT NEED TO DO ANYTHING HERE, I NEED TO DO IT AFTER ALL FIELDS ARE FULL
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapter) {  }
    });

https://play.golang.org/p/fHF_zrymcI