Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set any value to interface{}

Tags:

go

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

like image 218
Dmitry Maksimov Avatar asked Sep 18 '12 14:09

Dmitry Maksimov


People also ask

How do you assign a value to an interface?

To set default values for an interface in TypeScript, create an initializer function, which defines the default values for the type and use the spread syntax (...) to override the defaults with user-provided values. Copied!

CAN interfaces have default values?

Default values to an interface are not possible because interfaces only exists at compile time.

How would you define object type in interface TypeScript?

TypeScript Interface Type TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. To create an interface, use the interface keyword followed by the interface name and the typed object.

How do I create an interface object in TypeScript?

To create an object based on an interface, declare the object's type to be the interface, e.g. const obj1: Employee = {} . The object has to conform to the property names and the type of the values in the interface, otherwise the type checker throws an error.


2 Answers

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)
}
like image 128
thwd Avatar answered Sep 27 '22 22:09

thwd


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
}
like image 45
Denys Séguret Avatar answered Sep 27 '22 21:09

Denys Séguret