doujiufutaog59220 2017-08-01 20:56
浏览 21
已采纳

用可变的结构切片

In my func I have a variable of Product struct but I have not access to Product struct and I want make a slice of Product from it's variable for example:

test1 := Product{}

....
....
....

test2 := []TypeOf(test1)

how can I do that?

Update: what I want to actually achieve?

I have some structs that want to use in a adapter for gorm.

In my adapter for example I have a FindAll method that need slice of one of my struct.

All my structs is in a package named Domains and I don't want send needed variable from where use(call) FindAll function.

Now I registered all my structs to a Map and fetch them in adapter with struct name but the result is a variable of that struct not type of that struct so I can't make another variable from it or make a slice of that.

  • 写回答

2条回答 默认 最新

  • douna4762 2017-08-01 21:00
    关注

    You can do this using reflection, in particular TypeOf, SliceOf, and MakeSlice, however, it won't be very useful because you can only get a reference to it as an interface{}, which you can't use like a slice. Alternatively, you could assign it to a slice of type []interface{}, which would let you work with the slice, but again, without being able to reference the underlying type, you can't really do anything with the values. You might need to reconsider your design.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作