英文:
Golang type interface {} is interface with no methods
问题
目前我有类似这样的代码:
main.go
gojob.NewJob("every 2 second", "pene", func() {
t := gojob.Custom("pene")
log.Println(t)
}, struct {
Id int
}{
1,
})
我的gojob包如下:
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的函数每2秒在一个goroutine中执行一次,但我想访问我传递的匿名结构体...然而,当我尝试访问
t.Id
我得到了
t.Id undefined (type interface {} is interface with no methods)
然而,打印t给我了预期的结果
{1}
英文:
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}
答案1
得分: 28
你必须在访问其字段之前,将其 类型断言 为兼容的类型。
id := v.(struct{Id int}).Id
英文:
You have to type assert it to a compatible type before you can access its fields.
id := v.(struct{Id int}).Id
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论