Piston GenericEvent未针对事件

时间:2018-04-05 16:34:13

标签: rust rust-piston

我正在尝试使用 piston_window(0.77.0)库在Rust中编写游戏。从他们的hello world示例开始,我想我会首先将渲染逻辑分离为使用Event作为参数的方法,因为根据documentation它由window.next()返回。

use piston_window::*;

pub struct UI<'a> {
    window: &'a mut PistonWindow,
}

impl <'a> UI<'a> {
    pub fn new(window: &mut PistonWindow) -> UI {
        UI {
            window,
        }
    }

    fn render(&self, event: &Event) {
        self.window.draw_2d(&event, |context, graphics| {
            clear([1.0; 4], graphics);
            rectangle(
                [1.0, 0.0, 0.0, 1.0],
                [0.0, 0.0, 100.0, 100.0],
                context.transform,
                graphics);
            });
    }

    pub fn run(&mut self) {
        use Loop::Render;
        use Event::Loop;
        while let Some(event) = self.window.next() {
            match event {
                Loop(Render(_)) => self.render(&event),
                _ => {}
            }
        }
    }
}

然而,这会以错误结束:

  

self.window.draw_2d(&amp; event,| context,graphics | {
  piston_window::GenericEvent

未实施特征&piston_window::Event

没有提取渲染方法的代码按预期工作。

 pub fn run(&mut self) {
     use Loop::Render;
     use Event::Loop;
     while let Some(event) = self.window.next() {
         match event {
             Loop(Render(_)) => {
                 self.window.draw_2d(&event, |context, graphics| {
                     clear([1.0; 4], graphics);
                     rectangle(
                         [1.0, 0.0, 0.0, 1.0],
                         [0.0, 0.0, 100.0, 100.0],
                         context.transform,
                         graphics);
                 });

             },
             _ => {}
         }
     }
 }

我该如何提取这个?我有什么东西可以忽略吗?

1 个答案:

答案 0 :(得分:2)

event变量的类型为&Event,而非Event,因此您实际上是在尝试将&&Event传递给window.draw_2dEvent实现了GenericEvent&Event没有实现,这就是您看到错误的原因。

你只需要这样做:

self.window.draw_2d(event, |context, graphics| {
  ...
}

而不是:

self.window.draw_2d(&event, |context, graphics| {
  ...
}

为了公平对待Rust编译器,它还没有做更多的工作来指出你正确的方向。编译代码时,完整的错误消息是:

error[E0277]: the trait bound `&piston_window::Event: piston_window::GenericEvent` is not satisfied
  --> src/main.rs:34:21
   |
34 |         self.window.draw_2d(&event, |context, graphics| {
   |                     ^^^^^^^ the trait `piston_window::GenericEvent` is not implemented for `&piston_window::Event`
   |
   = help: the following implementations were found:
             <piston_window::Event as piston_window::GenericEvent>

最后一次&#34;帮助&#34;部分告诉您piston_window::Event 具有正确的实现,而前面的错误是&piston_window::Event没有。