Home >Backend Development >Golang >How Do I Convert a *foo Pointer to interface{} and Back in Go?
Converting Struct Pointers to Interface{}
Given immutable type declarations like the following:
type foo struct {} func bar(baz interface{}) {}
Where baz needs to be converted back to a *foo pointer within bar, this article explores how to convert &foo{} into an interface{} for use as a parameter in bar.
Cast &foo Pointer to interface{}**
Converting a *foo pointer to an interface{} is straightforward:
f := &foo{} bar(f) // Every type implements interface{}.
Converting interface{} Back to foo*
To retrieve the *foo value from the interface{}, two approaches are available:
Type Assertion:
func bar(baz interface{}) { f, ok := baz.(*foo) if !ok { // baz is not a *foo } // f is a *foo }
Type Switch:
func bar(baz interface{}) { switch f := baz.(type) { case *foo: // f is a *foo default: // f is some other type } }
The above is the detailed content of How Do I Convert a *foo Pointer to interface{} and Back in Go?. For more information, please follow other related articles on the PHP Chinese website!