Golang中的`interface{}`类型是一个没有方法的接口。

huangapple go评论94阅读模式
英文:

Golang type interface {} is interface with no methods

问题

目前我有类似这样的代码:

main.go

  1. gojob.NewJob("every 2 second", "pene", func() {
  2. t := gojob.Custom("pene")
  3. log.Println(t)
  4. }, struct {
  5. Id int
  6. }{
  7. 1,
  8. })

我的gojob包如下:

  1. func NewJob(t string, name string, c func(), v interface{}) {
  2. e := strings.Split(t, " ")
  3. job := process(e)
  4. job.log = false
  5. job.name = name
  6. job.action = c
  7. job.custom = v
  8. jobs = append(jobs, job)
  9. }
  10. func Custom(name string) interface{} {
  11. for i := range jobs {
  12. if jobs[i].name != name {
  13. continue
  14. }
  15. return jobs[i].custom
  16. }
  17. return nil
  18. }

问题是我传递给NewJob的函数每2秒在一个goroutine中执行一次,但我想访问我传递的匿名结构体...然而,当我尝试访问

  1. t.Id

我得到了

  1. t.Id undefined (type interface {} is interface with no methods)

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

  1. {1}
英文:

Currently Im having something like this

main.go

  1. gojob.NewJob("every 2 second", "pene", func() {
  2. t := gojob.Custom("pene")
  3. log.Println(t)
  4. }, struct {
  5. Id int
  6. }{
  7. 1,
  8. })

And my gojob package

  1. func NewJob(t string, name string, c func(), v interface{}) {
  2. e := strings.Split(t, " ")
  3. job := process(e)
  4. job.log = false
  5. job.name = name
  6. job.action = c
  7. job.custom = v
  8. jobs = append(jobs, job)
  9. }

And

  1. func Custom(name string) interface{} {
  2. for i := range jobs {
  3. if jobs[i].name != name {
  4. continue
  5. }
  6. return jobs[i].custom
  7. }
  8. return nil
  9. }

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

得分: 28

你必须在访问其字段之前,将其 类型断言 为兼容的类型。

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

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

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

huangapple
  • 本文由 发表于 2015年8月29日 02:48:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/32277884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定