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
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!
Default values to an interface are not possible because interfaces only exists at compile time.
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.
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.
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)
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With