duangu9997 2015-08-28 18:48
浏览 217
已采纳

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

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条回答 默认 最新

  • doudiaozhi6658 2015-08-28 18:58
    关注

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

    id := v.(struct{Id int}).Id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源