Currently Im having something like this
main.go
gojob.NewJob("every 2 second", "pene", func() {
t := gojob.Custom("pene")
log.Println(t)
}, struct {
Id int
}{
1,
})
And my gojob package
func NewJob(t string, name string, c func(), v interface{}) {
e := strings.Split(t, " ")
job := process(e)
job.log = false
job.name = name
job.action = c
job.custom = v
jobs = append(jobs, job)
}
And
func Custom(name string) interface{} {
for i := range jobs {
if jobs[i].name != name {
continue
}
return jobs[i].custom
}
return nil
}
Thing is the function Im passing to NewJob is beeing executed every 2 seconds on a goroutine but I want to access the anonymous struct I passed... however when I try to access
t.Id
Im getting
t.Id undefined (type interface {} is interface with no methods)
However printing t gives me the expected result
{1}
interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.
An interface in Go is a type defined using a set of method signatures. The interface defines the behavior for similar type of objects. An interface is declared using the type keyword, followed by the name of the interface and the keyword interface . Then, we specify a set of method signatures inside curly braces.
Since the interface is a type just like a struct, we can create a variable of its type. In the above case, we can create a variable s of type interface Shape .
You have to type assert it to a compatible type before you can access its fields.
id := v.(struct{Id int}).Id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With