The user with no hat
The user with no hat

Reputation: 10846

How to copy/clone an interface pointer?

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

Upvotes: 8

Views: 3028

Answers (1)

HectorJ
HectorJ

Reputation: 6324

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

Upvotes: 5

Related Questions