dongshetao1814 2016-04-11 16:20
浏览 43
已采纳

如何在Go中访问界面的字段?

I'm trying to do this:

if event.Type == sdl.QUIT {
    utils.Running = false
}

But I can't because when I try to build, I get this error:

 ./mm.go:11: event.Type undefined (type sdl.Event has no field or method Type)

Here is the relevant source code of the library I'm trying to use:

type Event interface{}    

type CEvent struct {
    Type uint32
    _    [52]byte // padding
}

type CommonEvent struct {
    Type      uint32
    Timestamp uint32
}

// WindowEvent (https://wiki.libsdl.org/SDL_WindowEvent)
type WindowEvent struct {
    Type      uint32
    Timestamp uint32
    WindowID  uint32
    Event     uint8
    _         uint8 // padding
    _         uint8 // padding
    _         uint8 // padding
    Data1     int32
    Data2     int32
}

As you can see, all of the other Events have the field Type. How can I access this?

Solution

This how I ended up polling events in this SDL2 binding for Go, in case anyone is wondering:

func PollEvents() {
    for {
        if event := sdl.PollEvent(); event != nil {
            switch event.(type) {
            case *sdl.QuitEvent:
                utils.Running = false
            }
        } else {
            break
        }
    }
}
  • 写回答

3条回答 默认 最新

  • douyue8685 2016-04-11 16:29
    关注

    You actually can't. Interfaces only define a method set that is available on a type, they do nothing to expose fields. In your case I would recommend doing a type switch. It would look a little like this;

         switch v := myInstance.(type) {
                    case CEvent:
                            fmt.Println(v)
                    case CommonEvent:
                            fmt.Println(v)
                    case WindowEvent:
                            fmt.Println(v)
                    default:
                            fmt.Println("unknown")
            }
    

    You may want to structure your code a bit differently depending on what you're doing with the instance after this but that gives you the basic idea. You can also do a type assertion with a single type like; v, err := myInstance.(CommonEvent) but I doubt it would be as effective here. It also returns an error if the type of myInstance is not CommonEvent so it's not really the best way to go about figuring out what type and interface instance may be.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改