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 找人不需要人工智能回答的gamit解算后做形变分析
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错