Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy/clone an interface pointer?

Tags:

go

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

like image 985
The user with no hat Avatar asked Oct 09 '15 03:10

The user with no hat


1 Answers

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)
}
like image 149
HectorJ Avatar answered Oct 06 '22 01:10

HectorJ