我有以下代碼:package mainimport ( "fmt")type Point struct { x,y int}func decode(value interface{}) { fmt.Println(value) // -> &{0,0} // This is simplified example, instead of value of Point type, there // can be value of any type. value = &Point{10,10}}func main() { var p = new(Point) decode(p) fmt.Printf("x=%d, y=%d", p.x, p.y) // -> x=0, y=0, expected x=10, y=10}我想將任何類型的值設置為傳遞給decode函數(shù)的值。在Go中有可能,還是我誤會了某些東西?http://play.golang.org/p/AjZHW54vEa
2 回答

慕妹3242003
TA貢獻1824條經(jīng)驗 獲得超6個贊
通常,僅使用反射:
package main
import (
"fmt"
"reflect"
)
type Point struct {
x, y int
}
func decode(value interface{}) {
v := reflect.ValueOf(value)
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
n := reflect.ValueOf(Point{10, 10})
v.Set(n)
}
func main() {
var p = new(Point)
decode(p)
fmt.Printf("x=%d, y=%d", p.x, p.y)
}

開心每一天1111
TA貢獻1836條經(jīng)驗 獲得超13個贊
我不確定您的確切目標。
如果您想斷言這value是指向Point它的指針并進行更改,則可以執(zhí)行以下操作:
func decode(value interface{}) {
p := value.(*Point)
p.x=10
p.y=10
}
- 2 回答
- 0 關(guān)注
- 207 瀏覽
添加回答
舉報
0/150
提交
取消