go - 设置指针的值不能通过接口(interface){}

标签 go

下面是来自 go 反射法则的稍微修改的示例 http://blog.golang.org/laws-of-reflection .第二个代码部分使用了来自 map[string]interface{} 的指针,但它不起作用,我做错了什么?

谢谢

//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}

}

最佳答案

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

尝试打印以下内容,您会看到想要看到的内容,但 x 不会改变,这意味着它永远不会更新。

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

您需要将指针传递给您的方法。将您的方法签名更改为如下所示

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

传递指针而不是副本。

我已经添加了一些打印语句,我认为它们有助于解决问题 http://play.golang.org/p/xcFMicIPcP

查看方法内部和外部的 x 的地址,看看它们有何不同。

关于go - 设置指针的值不能通过接口(interface){},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22139989/

相关文章:

go - 处理表单提交后提供页面时出现空白页面或运行时错误

go - WebSocket 何时使用关闭握手

javascript - 如何使用 go buffalo 框架渲染 quill js 内容

javascript - Jquery Ajax 不会返回数据(解析错误),但 Postman 成功

go - struct 到 bytes.Buffer{} 之后清理缓冲区

go - 无法在 Fedora 31 中安装 gopls

rest - 混合命名和未命名函数参数

go - 为什么 map 不返回它的值?

google-app-engine - 展平嵌套结构导致 slice 的 slice

go - go benchmark 中的 allocs/op 和 B/op 是什么意思?