It's easier to give an example than to explain. Given these typedefs
type myinterface interface {
foo()
}
type mytype struct {
x int
}
func (*mytype) foo() {}
I want to construct a function with this signature:
// if i is a type which implements myinterface, return it directly
// otherwise, if a pointer to it would implement myinterface, create that
// pointer and return it
// otherwise, return nil
func pointerize(i interface{}) myinterface { ... }
Calling pointerize on an instance of *mytype should return it, because that implements myinterface. Calling it on an instance of mytype should create *mytype, and then return that, because that implements myinterface.
I know how to construct a new instance of mytype and return that, but in order for that approach to work, I need generic deepcopy, which is hard. Given that getting a pointer to an instance is normally the single sigil &, this is turning out to be a much harder problem than I'd expected. playground
Some ways which also don't work:
- just using
&: playground - using
reflect.Value.Addr(): playground - using
unsafe.Pointer: playground
Aucun commentaire:
Enregistrer un commentaire