How to Access Custom Data in Goroutines with Type Interface {}?

Patricia Arquette
Release: 2024-11-03 20:13:03
Original
263 people have browsed it

How to Access Custom Data in Goroutines with Type Interface {}?

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>
Copy after login
<code class="go">func Custom(name string) interface{} {
    ...
    return jobs[i].custom
}</code>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!