Given the following code snippet:
type foo struct {} func bar(baz interface{}) {}
where both foo and bar are immutable by design, how can you convert a &foo{} struct pointer into an interface{} value and subsequently utilize it as a parameter for the bar function?
Casting a struct pointer to an interface{} value is straightforward:
f := &foo{} bar(f) // Every type implements interface{}, so no special action is required.
Recovering the original *foo pointer from the interface{} value requires either type assertion or a type switch.
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. } }
The above is the detailed content of How Can I Convert a Struct Pointer to an interface{} Value in Go?. For more information, please follow other related articles on the PHP Chinese website!