Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang type interface {} is interface with no methods

Tags:

interface

go

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}

like image 723
Raggaer Avatar asked Aug 28 '15 18:08

Raggaer


People also ask

What is [] interface {} Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.

How do you declare a variable of type interface in Golang?

An interface in Go is a type defined using a set of method signatures. The interface defines the behavior for similar type of objects. An interface is declared using the type keyword, followed by the name of the interface and the keyword interface . Then, we specify a set of method signatures inside curly braces.

Can a Golang interface have variables?

Since the interface is a type just like a struct, we can create a variable of its type. In the above case, we can create a variable s of type interface Shape .


1 Answers

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

id := v.(struct{Id int}).Id
like image 53
OneOfOne Avatar answered Sep 21 '22 18:09

OneOfOne