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

Rag*_*aer 10 interface go

目前我有类似的东西

main.go

gojob.NewJob("every 2 second", "pene", func() {
        t := gojob.Custom("pene")
        log.Println(t)
    }, struct {
        Id int
    }{
        1,
    })
Run Code Online (Sandbox Code Playgroud)

我的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)
}
Run Code Online (Sandbox Code Playgroud)

func Custom(name string) interface{} {
    for i := range jobs {
        if jobs[i].name != name {
            continue
        }
        return jobs[i].custom
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

事情是我传递给NewJob的函数是每两秒在goroutine执行但我想访问我传递的匿名结构...但是当我尝试访问

t.Id

我越来越

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

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

{1}

One*_*One 23

在访问其字段之前,必须键入断言为兼容类型.

id := v.(struct{Id int}).Id
Run Code Online (Sandbox Code Playgroud)

  • 对不起,但你的意思是["类型断言"](http://golang.org/ref/spec#Type_assertions)(因为"铸造"可能意味着不同的东西) (4认同)