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

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

Golang type interface {} is interface with no methods

问题

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

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的函数每2秒在一个goroutine中执行一次,但我想访问我传递的匿名结构体...然而,当我尝试访问

t.Id

我得到了

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

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

{1}
英文:

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

得分: 28

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

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

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

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:

确定