foo.Name未定义(类型接口{}没有字段或方法名称)

foo.Name未定义(类型接口{}没有字段或方法名称)

问题描述:

I use the native golang package "container/list" to manage inotify event in a stack. When I access at stack's item, I have a fail with the type (I think).

import (
    "golang.org/x/exp/inotify" 
    "container/list"
    "log"
    "fmt"
)

func main() {
    stack := list.New()
    watcher, err := inotify.NewWatcher()

    if err != nil {
        log.Fatal(err)
    }

   err = watcher.Watch(os.Args[1])
   if err != nil {
       log.Fatal(err)
   }

   for {
       select {
           case ev := <-watcher.Event:
               stack.PushFront(ev)

               fmt.Printf("%#v
", ev)
        }

        foo := stack.Front().Value

        fmt.Printf("%#v
", foo)
        log.Println("Name: ", foo.Name)
    }
}

When I dump ev variable, the object type is &inotify.Event. When I pop one item and I dump the variable, my object type is &inotify.Event.

With the error message I think it's a problem with type object accept by interface but I don't find how define type.

You need to do type-assertion for foo into *inotify.Event, the stack doesn't know what it is, it just holds interface{} objects.

What you need to do is something like:

elem := stack.Front().Value
if foo, ok := elem.(*inotify.Event); ok {
       fmt.Printf("%#v
", foo)
       log.Println("Name: ", foo.Name)
}

The ok bit makes sure if it's not an event, your program won't crash. Of course you need to handle the case that it isn't.

More info on interface conversions and type assertions: https://golang.org/doc/effective_go.html#interface_conversions