drq1257 2015-01-16 21:12 采纳率: 0%
浏览 40
已采纳

如何从接口{}获取结构成员的指针

I want to pass struct's pointer to function that expect interface{}. Then get (through reflection) the pointer to the struct's member and then modify it using this pointer. I've read a much of Q&A and tried much of variations, but still I can get it work.

Let's consider example below:

type Robot struct {
    Id int
}
f := func(i interface {}) {
    v :=  reflect.ValueOf(i).Elem().FieldByName("Id")
    ptr := v.Addr().Pointer()
    *ptr = 100
    //^ it needs to me for functions expecting the pointer: Scan(&pointerToValue)
}

robot := &Robot{}
f(robot)
println(robot.Id) //I want to get here 100

I think the problem in poor understanding what actually do Addr() and Pointer() methods of reflect package..

  • 写回答

1条回答 默认 最新

  • doumi7861 2015-01-16 21:19
    关注

    Here's a working version of function f:

    func f(i interface{}) {
      v := reflect.ValueOf(i).Elem().FieldByName("Id")
      ptr := v.Addr().Interface().(*int)
      *ptr = 100
    }
    

    playground example

    The conversion to integer pointer goes as follows:

    • v is a reflect.Value representing the int field.
    • v.Addr() is a relfect.Value representing a pointer to the int field.
    • v.Addr().Interface() is an interface{} containing the int pointer.
    • v.Addr().Interface().(*int) type asserts the interface{} to a *int

    You can set the field directly without getting a pointer:

    func f(i interface{}) {
      v := reflect.ValueOf(i).Elem().FieldByName("Id")
      v.SetInt(100)
    }
    

    playground example

    If you are passing the value along to something expecting interface{} (like the db/sql Scan methods), then you can remove the type assertion:

    func f(i interface{}) {
      v := reflect.ValueOf(i).Elem().FieldByName("Id")
      scan(v.Addr().Interface())
    }
    

    playground example

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

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染