Accessing Anonymous Structs Passed as Interface{} in Golang
In Go, it is possible to define an interface with no methods using the syntax interface{}. However, working with types that implement such an interface can present challenges, particularly when attempting to access fields of an anonymous struct.
Consider the following example where you want to pass an anonymous struct as a parameter to a function:
<code class="go">package main import ( "fmt" "log" "time" ) type job struct { name string action func() custom interface{} } func NewJob(t string, name string, c func(), v interface{}) { job := process(t) job.name = name job.action = c job.custom = v go func() { for { job.action() time.Sleep(2 * time.Second) } }() } func Custom(name string) interface{} { for _, j := range jobs { if j.name != name { continue } return j.custom } return nil } func main() { NewJob("every 2 second", "pene", func() { t := Custom("pene") log.Println(t) }, struct { ID int }{ 1, }) }</code>
In this example, the NewJob function takes an interface{} type parameter called v. Inside the function, you set the custom field of a job struct to v. You then launch the job with a goroutine that executes the provided function every two seconds. Within the goroutine, you retrieve the custom field using the Custom function and attempt to access the ID field of the anonymous struct. However, you'll encounter an error:
t.ID undefined (type interface {} is interface with no methods)
This is because the interface{} type does not have any methods, so you cannot directly access fields of the underlying type. To resolve this, you must first "type assert" the interface to the appropriate type before you can access its fields. In this case, you know the underlying type is the anonymous struct {ID int}, so you can type assert it as follows:
<code class="go">id := v.(struct{ID int}).ID</code>
By type asserting v to the correct struct type, you can now access the ID field as expected.
The above is the detailed content of How to Access Fields of an Anonymous Struct Passed as `interface{}` in Golang?. For more information, please follow other related articles on the PHP Chinese website!