为了账号安全,请及时绑定邮箱和手机立即绑定

如何从接口{}值(反射)为显式类型的结构成员设置新值?

如何从接口{}值(反射)为显式类型的结构成员设置新值?

Go
千巷猫影 2021-09-10 21:27:22
我想了解使用反射包的一些微妙时刻。请参阅下面的示例,它更好地描述了我想知道的内容:type Robot struct {    id    int    model string}func change(i interface{}, fields ...string) {        v := reflect.ValueOf(i).Elem()        // here I emulate function by slice that could return any value,        // so here I need to check if I can store incoming values to existing struct        returns := []interface{}{100, "Something"}        for i, name := range fields {            x := reflect.ValueOf(&returns[i]).Elem()            //check if value representing x is the same of struct member            v.FieldByName(name).Set(x)            // ^ here I want to store 100 to Robot.id when i = 0,            // and "Something" to Robot.model when i = 1        }}func main() {    robot := &Robot{id: 1, model: "T310"}    change(robot, "model", "id")    // now robot become as follows: &Robot{100, "Something"}}为什么需要呢?    // It is need for retrieving values from sql DB into struct members     // (only for training purposes :))    // Example:    f := func(q string, structs interface{}, fields ...string) {        rows, _ := db.Query(q)        for i := 0; rows.Next(); i++ {            rows.Scan(&structs[i])            // very dirty here! it's hard to understand how to implement it        }    }    var robots = []*Robot    f("select id, model from robots", robots, "id", "model")    // now each member of robots var should contain values from DB我试图描述性并尽可能简短地解释。我希望你能理解我..
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 141 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信