2014-03-03 21 views
0

不起作用下面是來自反射法則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} 

} 

回答

2

該界面v包含或ELEM返回值,所述指針V形尖端到。

嘗試打印以下內容,您將看到要查看的內容,但x不會更改,這意味着它不會被更新。

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

您需要將指針傳遞給您的方法。改變你的方法簽名看起來像這樣

​​

傳遞一個指針而不是副本。

我補充說,我認爲這將有助於清楚的事情了http://play.golang.org/p/xcFMicIPcP

看的x內部地址和外界的方法,看看他們是怎麼不同的一些打印語句。