How to copy an interface value in Go?
My User interface:
type User interface {
Name() string
SetName(name string)
}
There is a more generic way to do that.
func Clone(oldObj interface{}) interface{} {
newObj := reflect.New(reflect.TypeOf(oldObj).Elem())
oldVal := reflect.ValueOf(oldObj).Elem()
newVal := newObj.Elem()
for i := 0; i < oldVal.NumField(); i++ {
newValField := newVal.Field(i)
if newValField.CanSet() {
newValField.Set(oldVal.Field(i))
}
}
return newObj.Interface()
}
However, it has one pitfall: it cannot set unexported fields. It can be worked around using this solution with the help of unsafe's black magic, but I would rather avoid it.