Rust 中的闭包就像高级语言中的那样

问题描述 投票:0回答:1

所以,我是 Rust 和低级编程的新手。我正在学习 Rust 用 sdl2 制作简单的游戏。我的项目架构如下: 主要.rs

void main() -> Result((), String) {
  let mut window = CWindow::new("Playground", 1080, 720);

  let rects: Vec<Rect> = ... // Data i wanna have in update

  window.set_update(|| update(rects)); // trying wrap my update so i can pass rects. THE PROBLEM IS HERE
  window.set_draw(draw);
  window.init()?;
}

fn draw(canvas: &mut Canvas<Window>) -> () {
  //some draw
}

fn update(Vec<Rect>) -> () {
  //some update
}

cwindow.rs

pub struct CWindow {
    title: String,
    width: u32,
    height: u32,
    callbacks: CWindowCallbacks,
    window: Option<Window>,
}

pub struct CWindowCallbacks {
    update: Option<fn() -> ()>,
    draw: Option<fn(&mut Canvas<Window>) -> ()>,
}

impl CWindow {
    pub fn new(title: &str, width: u32, height: u32) -> CWindow {
        CWindow {
            title: String::from(title),
            width: width,
            height: height,
            callbacks: CWindowCallbacks {
                draw: None,
                update: None,
            },
            window: None,
        }
    }

    pub fn init(&self) -> Result<(), String> {
        if self.callbacks.draw.is_none() {
            panic!("Need draw callback")
        }
        if self.callbacks.update.is_none() {
            panic!("Need update callback")
        }
        //...
        //sdl init stuff
        //...


        'running: loop {
             
            //...
            //handling events
            //...

            self.callbacks.update.unwrap()();
            self.callbacks.draw.unwrap()(&mut canvas);
        }
        Ok(())
    }

    pub fn set_draw(&mut self, draw: fn(&mut Canvas<Window>) -> ()) {
        self.callbacks.draw = Some(draw);
    }

    pub fn set_update(&mut self, update: fn() -> ()) {
        self.callbacks.update = Some(update);
    }
}

锈迹分析仪显示“类型不匹配 预期的 fn 指针

fn()
发现闭包 `{closure@src\main.rs:15:23: 15:25}"

总而言之:如何包装我的更新以便我可以传递数据?

rust closures
1个回答
0
投票

虽然特征 fn 和 Fn 看起来很相似,但它们并不相同。

特征 Fn、FnMut 和 FnOnce 都代表闭包,而 fn 代表函数。

这个 rust-lang 章节有一些关于闭包的非常好的信息: https://doc.rust-lang.org/rust-by-example/fn/closures/input_parameters.html

© www.soinside.com 2019 - 2024. All rights reserved.