下面是来自 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/