目前我有这样的事情
main.go
gojob.NewJob("every 2 second", "pene", func() {
t := gojob.Custom("pene")
log.Println(t)
}, struct {
Id int
}{
1,
})
还有我的工作包
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)
}
还有
func Custom(name string) interface{} {
for i := range jobs {
if jobs[i].name != name {
continue
}
return jobs[i].custom
}
return nil
}
事情是我传递给 NewJob 的函数在 goroutine 上每 2 秒执行一次,但我想访问我传递的匿名结构......但是当我尝试访问时
t.Id
我来了
t.Id undefined (type interface {} is interface with no methods)
但是打印 t 给了我预期的结果
{1}
最佳答案
你必须 type assert在您可以访问其字段之前,将其转换为兼容的类型。
id := v.(struct{Id int}).Id
关于Golang type interface {} 是没有方法的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32277884/