I'm trying to make a copy of a pointer received as interface{}. Any idea how to do that? I've tried Reflect.Value.Interface() but it returns the pointer/ address itself instead to return its value (deference). I'm also wondering if there is a signifiant performance loss as I'm planning doing this kind of copy vs simple pointer deference.
package main
import "fmt"
import "reflect"
type str struct {
field string
}
func main() {
s := &str{field: "astr"}
a := interface{}(s)
v := reflect.ValueOf(a)
s.field = "changed field"
b := v.Interface()
fmt.Println(a, b)
}
http://play.golang.org/p/rFmJGrLVaa
You need reflect.Indirect, and also to set b
before changing s.field
.
Here is some working code :
https://play.golang.org/p/PShhvwXjdG
package main
import "fmt"
import "reflect"
type str struct {
field string
}
func main() {
s := &str{field: "astr"}
a := interface{}(s)
v := reflect.Indirect(reflect.ValueOf(a))
b := v.Interface()
s.field = "changed field"
fmt.Println(a, b)
}
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