Accessing Custom Data in Goroutine with Type Interface {}
In some scenarios, you may encounter a situation where you need to access data passed as an anonymous struct to a goroutine running a scheduled job using gojob. However, accessing its fields directly results in the error "type interface {} is interface with no methods."
To resolve this issue, you must explicitly typecast the interface{} custom data to the correct type before accessing its fields. Here's how you can modify your code:
<code class="go">func NewJob(t string, name string, c func(), v interface{}) { ... jobs = append(jobs, job) }</code>
<code class="go">func Custom(name string) interface{} { ... return jobs[i].custom }</code>
Now, within the scheduled goroutine, you can access the anonymous struct's field by typecasting it:
<code class="go">id := v.(struct{Id int}).Id</code>
This explicit type assertion ensures that you can access the Id field without encountering the "undefined" error.
The above is the detailed content of How to Access Custom Data in Goroutines with Type Interface {}?. For more information, please follow other related articles on the PHP Chinese website!