douzhantao2857 2014-03-03 06:21
浏览 3
已采纳

设置指针的值无法通过接口{}使用

Below is slightly modified example from the go laws of reflection http://blog.golang.org/laws-of-reflection. The 2nd code section uses a pointer from a map[string]interface{} and it does not work, what am I doing wrong?

Thanks

//http://play.golang.org/p/LuMBUWLVT6
package main

import (
  "fmt"
  "reflect"
)

type T struct {
  x float64
}

func (x T) RowMap() map[string]interface{} {
  return map[string]interface{}{
    "x": &x.x,
  }
}

func main() {

  // this section works as expected, x.x will be 7.1 when done
  var x = T{3.4}
  p := reflect.ValueOf(&x.x) // Note: take the address of x.
  v := p.Elem()
  v.SetFloat(7.1)
  fmt.Println(x.x, x) // 7.1 {7.1}

  // this section I do not understand why x.x is not being set to 7.1
  x = T{3.4}
  rowmap := x.RowMap()
  p = reflect.ValueOf(rowmap["x"]) // rowmap["x"] => &x.x just like above, but is containted in interface{}
  v = p.Elem()
  v.SetFloat(7.1)
  fmt.Println(x.x, x) // 3.4 {3.4}  ?? huh, should be // 7.1 {7.1}

}
  • 写回答

1条回答 默认 最新

  • doujiao1180 2014-03-03 06:55
    关注

    Elem returns the value that the interface v contains or that the pointer v points to.

    Try printing the following and you'll see what you want to see but x does not change meaning it's never being updated.

    fmt.Println(v.Float()) // 7.1
    

    You need to pass a pointer to your method. Change your method signature to look like this

    func (x *T) RowMap() map[string]interface{} {
    

    Pass a pointer instead of a copy.

    I've added some print statements that I think will help clear things up http://play.golang.org/p/xcFMicIPcP

    Look at the address of x inside and outside of your method and see how they're different.

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口