Home >Backend Development >Golang >How Can I Cast a Struct Pointer to an Interface{} and Back in Go?

How Can I Cast a Struct Pointer to an Interface{} and Back in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 09:30:11879browse

How Can I Cast a Struct Pointer to an Interface{} and Back in Go?

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!

Statement:
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