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 win2012 iscsi ipsec
  • ¥15 封装的 matplotlib animation 不显示图像
  • ¥15 python摄像头画面无法显示
  • ¥15 关于#3d#的问题:d标定算法(语言-python)
  • ¥15 cve,cnnvd漏洞扫描工具推荐
  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)