douleijiang8111 2016-11-07 21:10
浏览 24
已采纳

将结构切片值设置为结构,而无需类型声明(因为它是未知的)

I'm creating a helper package to pop payloads from a queue. It's essential that this helper be agnostic to the struct used by the application importing it.

This (no-op, just example) function will provide a single payload from the queue, of the provided type like interface{}:

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

    return one.Interface()
}

This function provides many payloads:

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

An example of usage is:

type Payload struct {
    Id int
    Text string
}

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

However, the above results in:

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

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

  • 写回答

1条回答 默认 最新

  • douzhi4991 2016-11-07 21:17
    关注

    You're calling reflect.TypeOf on a reflect.Value, which is where **reflect.rtype is coming from.

    Call your One function wth the like value directly, and assign that result to the 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭