How to Access Anonymous Struct Values Within an `interface{}` in Golang?

Susan Sarandon
Release: 2024-11-04 04:17:29
Original
350 people have browsed it

How to Access Anonymous Struct Values Within an `interface{}` in Golang?

Accessing Anonymous Struct Values in Golang Type Interface {}

You're facing an issue accessing the anonymous struct you passed to the NewJob function from within the Custom function. The error you're encountering, "interface {} is interface with no methods," indicates that the interface{} type you're working with has no defined methods, making it impossible to access fields directly.

To resolve this, you need to type assert the interface{} value to a compatible type, such as the anonymous struct your data belongs to. Doing so allows you to access the field you desire. Here's the adjusted code:

<code class="go">func Custom(name string) interface{} {
    for i := range jobs {
        if jobs[i].name != name {
            continue
        }
        return jobs[i].custom
    }
    return nil
}

...

id := t.(struct{Id int}).Id</code>
Copy after login

In the above code, we type assert t to a struct with a field named Id. This allows us to access the Id field directly, now returning the expected result of 1.

The above is the detailed content of How to Access Anonymous Struct Values Within an `interface{}` in Golang?. 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