6

私は次のコードを持っています:

package main

import (
   "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。Goでそれは可能ですか、それとも私は何かを誤解していますか?

http://play.golang.org/p/AjZHW54vEa

4

2 に答える 2

5

一般的に、反射のみを使用します:

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)
}
于 2012-09-18T14:26:44.190 に答える
1

あなたの正確な目標はわかりません。

それがポインタであると主張して変更したい場合は、次のようにすることができます。valuePoint

func decode(value interface{}) {
    p := value.(*Point)
    p.x=10
    p.y=10
}
于 2012-09-18T14:17:26.420 に答える