douren2831 2015-06-24 12:45
浏览 31
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dsfsw1233 2015-06-24 12:52
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了