Casting a Struct Pointer to an Interface
Given that the struct foo and the function bar have inflexible definitions, this question seeks a solution to convert a pointer to foo into an interface{} for use as a parameter in bar. Additionally, the conversion back to a foo struct pointer within bar is necessary.
Conversion to Interface{}
To convert &foo{} into an interface{}, the process is straightforward:
f := &foo{} bar(f) // Every type implements interface{}.
Conversion Back to *foo
To retrieve the original *foo from the interface{}, two methods are available:
Type Assertion
func bar(baz interface{}) { f, ok := baz.(*foo) if !ok { // baz was not of type *foo. The assertion failed. } // f is of type *foo }
Type Switch
func bar(baz interface{}) { switch f := baz.(type) { case *foo: // f is of type *foo default: // f is some other type } }
The above is the detailed content of How Can I Cast a Struct Pointer to an Interface{} and Back in Go?. For more information, please follow other related articles on the PHP Chinese website!