Home > Backend Development > Golang > How Do I Convert a *foo Pointer to interface{} and Back in Go?

How Do I Convert a *foo Pointer to interface{} and Back in Go?

Patricia Arquette
Release: 2024-12-02 16:23:12
Original
708 people have browsed it

How Do I Convert a *foo Pointer to interface{} and Back in Go?

Converting Struct Pointers to Interface{}

Given immutable type declarations like the following:

type foo struct {}

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

Where baz needs to be converted back to a *foo pointer within bar, this article explores how to convert &foo{} into an interface{} for use as a parameter in bar.

Cast &foo Pointer to interface{}**

Converting a *foo pointer to an interface{} is straightforward:

f := &foo{}
bar(f) // Every type implements interface{}.
Copy after login

Converting interface{} Back to foo*

To retrieve the *foo value from the interface{}, two approaches are available:

Type Assertion:

func bar(baz interface{}) {
    f, ok := baz.(*foo)
    if !ok {
        // baz is not a *foo
    }

    // f is a *foo
}
Copy after login

Type Switch:

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

The above is the detailed content of How Do I Convert a *foo Pointer to 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