Home > Backend Development > Golang > How to Access Fields of an Anonymous Struct Passed as `interface{}` in Golang?

How to Access Fields of an Anonymous Struct Passed as `interface{}` in Golang?

Mary-Kate Olsen
Release: 2024-11-03 22:05:30
Original
909 people have browsed it

How to Access Fields of an Anonymous Struct Passed as `interface{}` in Golang?

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

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

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

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!

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