copy pointer values *a = *b in golang

Generic solution for framework developers :

func Copy(source interface{}, destin interface{}) {
    x := reflect.ValueOf(source)
    if x.Kind() == reflect.Ptr {
        starX := x.Elem()
        y := reflect.New(starX.Type())
        starY := y.Elem()
        starY.Set(starX)
        reflect.ValueOf(destin).Elem().Set(y.Elem())
    } else {
        destin = x.Interface()
    }
}

So:

Copy(old, new)
see this code in play.golang.org So you can pass any type at run time as long as you're sure that source and destin are both of the same type, (and destin is a pointer to that type).

Your first example is almost right. You pass in pointers to two objects. You put those pointers into variables A and B. But A and B are local variables, so when you say a=b you are merely saying "forget what was in A (locally)". The rest of the program still has pointers to those two original objects.

If you want to copy the data structure at B into the data structure at A, do this instead:

*a = *b;

As dmikalova pointed out in the comments below, this merely copies the structs -- but not any data the struct points to. If your struct has a pointer, the data it points to is now shared by the two copies (because it only copied the pointer).

Technically, strings are always pointers, so they are never copied as part of your struct. But because strings are immutable (and Go has Garbage Collection), strings "feel" like they are part of your struct, and you don't have to worry about the low-level string sharing that magically saves you memory without you having to think about it.

Tags:

Go