Golang类型接口{}是没有方法的接口

时间:2015-08-28 18:48:27

标签: go interface

目前我有类似的东西

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的函数每两秒在goroutine上执行但是我想访问我传递的匿名结构...但是当我尝试访问时

  

t.Id

我得到了

  

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

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

  

{1}

1 个答案:

答案 0 :(得分:22)

在访问其字段之前,您必须type assert将其设置为兼容类型。

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