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
Release: 2024-12-11 09:30:11
Original
857 people have browsed it

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

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
}
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 Cast a Struct Pointer to an Interface{} and Back 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