Converting Struct Pointer to Interface
Consider the following scenario:
type foo struct{} func bar(baz interface{}) {}
Given that foo and bar are immutable and baz must be restored to a foo struct pointer in bar, the issue arises: how can you cast &foo{} to interface{} for use as a parameter in bar?
Solution
Casting &foo{} to interface{} is straightforward:
f := &foo{} bar(f) // Every type implements interface{}. No special action is needed.
To return to *foo, you can perform either:
Type Assertion
func bar(baz interface{}) { f, ok := baz.(*foo) if !ok { // The assertion failed because baz was not of type *foo. } // 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 } }
By utilizing these techniques, you can successfully convert struct pointers to interfaces and restore them back to struct pointers within functions.
The above is the detailed content of How Can I Safely Convert a Struct Pointer to an Interface and Back in Go?. For more information, please follow other related articles on the PHP Chinese website!