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>
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!