Golang类型接口{}是没有方法的接口 [英] Golang type interface {} is interface with no methods

查看:1457
本文介绍了Golang类型接口{}是没有方法的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有这样的东西



main.go

  gojob.NewJob(每2秒,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自定义(名称字符串)界面{} {
for i:=范围jobs {
如果jobs [i] .name!= name {
continue
}
return jobs [i] .custom
}
返回nil
}

Thing是Im传递给New的函数作业是beeing在goroutine上每2秒钟执行一次,但我想访问我通过的匿名结构...但是,当我尝试访问时


t.Id


进入


t.Id undefined(type interface {}是没有方法的接口)

然而,打印t给了我预期的结果


{1}



解决方案您必须先键入断言到兼容的类型,然后才能访问其字段。

  id:= v。(struct {Id int})。Id 


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}

解决方案

You have to type assert it to a compatible type before you can access its fields.

id := v.(struct{Id int}).Id

这篇关于Golang类型接口{}是没有方法的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆