Please ignore that this seems like a bad idea, is bad style, etc.
The main issue here is that process()
gets a pointer to a struct of an unknown type passed in as interface{}
and I need to clone the underlying struct.
The core issue is that I can't figure out how to deference the pointer, since its passed in as interface{}
, so I can clone the underlying struct and return it.
package main
import (
"fmt"
"reflect"
)
type Foo struct {
Value string
}
func main() {
foo1 := Foo{"bar"}
foo2 := process(&foo1)
result := reflect.DeepEqual(foo1, foo2)
fmt.Println(result) // how do I make this true?
}
// objective: pointer to struct is passed it, clone of underlying struct is returned
func process(i interface{}) interface{} {
return clone(i)
}
Using some reflection magic, I was able to get this to work. Thanks, JimB, for all your help! The code in this question is obviously contrived. I need this functionality for a testing utility that takes "snapshots" of structs of any type at different stages before various mutations are applied.
...
func process(i interface{}) (interface{}, error) {
value := reflect.ValueOf(i)
if value.Kind() == reflect.Ptr {
i = value.Elem().Interface()
}
return copystructure.Copy(i)
}
...