Home > Backend Development > Golang > How Can I Safely Convert a Struct Pointer to an Interface and Back in Go?

How Can I Safely Convert a Struct Pointer to an Interface and Back in Go?

Mary-Kate Olsen
Release: 2024-12-13 16:41:10
Original
339 people have browsed it

How Can I Safely Convert a Struct Pointer to an Interface and Back in Go?

Converting Struct Pointer to Interface

Consider the following scenario:

type foo struct{}

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

Given that foo and bar are immutable and baz must be restored to a foo struct pointer in bar, the issue arises: how can you cast &foo{} to interface{} for use as a parameter in bar?

Solution

Casting &foo{} to interface{} is straightforward:

f := &foo{}
bar(f) // Every type implements interface{}. No special action is needed.
Copy after login

To return to *foo, you can perform either:

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

By utilizing these techniques, you can successfully convert struct pointers to interfaces and restore them back to struct pointers within functions.

The above is the detailed content of How Can I Safely Convert 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