Home > Backend Development > Golang > How Can I Convert a Struct Pointer to an interface{} Value in Go?

How Can I Convert a Struct Pointer to an interface{} Value in Go?

Mary-Kate Olsen
Release: 2024-12-01 03:14:10
Original
522 people have browsed it

How Can I Convert a Struct Pointer to an interface{} Value in Go?

Converting Struct Pointers to Interface{} Values

Given the following code snippet:

type foo struct {}

func bar(baz interface{}) {}
Copy after login

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?

Solution

Casting a struct pointer to an interface{} value is straightforward:

f := &foo{}
bar(f) // Every type implements interface{}, so no special action is required.
Copy after login

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.
}
Copy after login

Type Switch:

func bar(baz interface{}) {
    switch f := baz.(type) {
    case *foo: // f is of type *foo.
    default: // f is some other type.
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template