gpt4 book ai didi

go - reflect.Set slice-of-structs value to a struct,没有类型断言(因为它是未知的)

转载 作者:IT王子 更新时间:2023-10-29 02:33:02 28 4
gpt4 key购买 nike

我正在创建一个帮助包来从队列中弹出负载。重要的是,此帮助程序与导入它的应用程序使用的结构无关。

此(无操作,仅作为示例)函数将从队列中提供一个有效负载,其类型为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

最佳答案

您正在 reflect.Value 上调用 reflect.TypeOf,这是 **reflect.rtype 的来源。

直接使用 like 值调用您的 One 函数,并将该结果分配给 slice 。

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()
}

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

关于go - reflect.Set slice-of-structs value to a struct,没有类型断言(因为它是未知的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474682/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com