Golang type interface {} is interface with no methods

我是研究僧i 提交于 2019-12-10 02:11:56

问题


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:


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

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


来源:https://stackoverflow.com/questions/32277884/golang-type-interface-is-interface-with-no-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!