1

我正在尝试使用活塞窗口(0.77.0)库在 Rust 中编写游戏。从他们的hello world示例开始,我想我会先将渲染逻辑分离为使用 Event 作为参数的方法,因为根据文档,它是由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(&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);
                 });

             },
             _ => {}
         }
     }
 }

我怎样才能提取这个?有什么我忽略的吗?

4

1 回答 1

2

event变量具有类型&Event,而不是Event,因此您实际上是在尝试传递&&Eventto 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>

最后一个“帮助”部分告诉您piston_window::Event 确实有正确的实现,而前面的错误是说&piston_window::Event没有。

于 2018-04-05T17:56:02.510 回答