Dmitry Maksimov
Dmitry Maksimov

Reputation: 2861

How to set any value to interface{}

I have following code:

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
}

I want to set value of any type to the value passed to decode function. Is it possible in Go, or I misunderstand something?

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

Upvotes: 6

Views: 303

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382264

I'm not sure of your exact goal.

If you want to assert that value is a pointer to Point and change it, you can do that :

func decode(value interface{}) {
    p := value.(*Point)
    p.x=10
    p.y=10
}

Upvotes: 1

thwd
thwd

Reputation: 24848

Generically, only using reflection:

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

Upvotes: 5

Related Questions