6

I am just learning Rust. I am trying to create a builder struct for my Game struct. Here is the code:

struct Input {
    keys_pressed: HashMap<VirtualKeyCode, bool>,
}

pub struct GameBuilder {
    settings: GameSettings,
    input: Input,
}

impl GameBuilder {
    pub fn new() -> GameBuilder {
        GameBuilder {
            settings: GameSettings {
                window_dimensions: (800, 600),
                title: "".to_string(),
            },
            input: Input {
                keys_pressed: HashMap::new(),
            }
        }
    }

    pub fn with_dimensions(&mut self, width: u32, height: u32) -> &mut GameBuilder {
        self.settings.window_dimensions = (width, height);
        self
    }

    pub fn with_title(&mut self, title: &str) -> &mut GameBuilder {
        self.settings.title = title.to_string();
        self
    }

    pub fn game_keys(&mut self, keys: Vec<VirtualKeyCode>) -> &mut GameBuilder {
        for key in keys {
            self.input.keys_pressed.insert(key, false);
        }
        self
    }

    pub fn build(&self) -> Game {
        let (width, height) = self.settings.window_dimensions;
        Game {
            display: glutin::WindowBuilder::new()
                        .with_dimensions(width, height)
                        .with_title(self.settings.title.to_string())
                        .build_glium()
                        .ok()
                        .expect("Error in WindowBuilder"),
            state: GameState::Running,
            input: self.input,
        }
    }
}

But this code complains in the last line input: self.input with this:

error: cannot move out of borrowed content

I think I understand why. Since the argument passed in the function is &self, I cannot take ownership of it, and that what the last line is doing.

I thought that maybe changing &self to self would work, but then the compile argues that I cannot mutate self.

There is also the Copy trait from what I know, and that maybe should solve the problem. But Input is basically a HashMap, which means that a copy could be expensive if the hash itself is too big.

How would be a nice way of solving this problem?

Edit:

I tried doing this:

#[derive(Debug, Copy, Clone)]
struct Input {
    keys_pressed: HashMap<VirtualKeyCode, bool>,
}

But the compiler complains:

error: the trait `Copy` may not be implemented for this type; field `keys_pressed` does not implement `Copy`
4

2 回答 2

7

鉴于您的方法签名是如何制定的,您的目标似乎是链接:

let game = GameBuilder::new().with_dimensions(...)
                             .with_title(...)
                             .build();

在 Rust 中,这要求GameBuilder按值传递:

pub fn with_dimensions(self, ...) -> GameBuilder {
    // ...
}

为了能够self在方法内进行变异,您需要使它mut

pub fn with_dimensions(mut self, ...) -> GameBuilder {
}

如果您更改 , 和 的签名with_dimensionswith_titlegame_keysbuild获取selfmut self如果打算进行突变),则链接应该可以工作。

于 2015-08-06T15:07:37.600 回答
0

Option使用and尝试构建器模式take()

例子:

#[derive(PartialEq, Debug)]
struct Game {
    window: Window,
}

#[derive(PartialEq, Debug)]
struct Window {
    title: String,
    dimensions: (u32, u32),
}

struct GameBuilder {
    window_title: Option<String>,
    window_dimensions: Option<(u32, u32)>,
}

impl GameBuilder {
    fn new() -> Self {
        Self {
            window_title: None,
            window_dimensions: None,
        }
    }

    fn window_title(&mut self, window_title: &str) -> &mut Self {
        self.window_title = Some(window_title.to_owned());
        self
    }

    fn window_dimensions(&mut self, width: u32, height: u32) -> &mut Self {
        self.window_dimensions = Some((width, height));
        self
    }

    fn build(&mut self) -> Result<Game, Box<dyn std::error::Error>> {
        Ok(Game {
            window: Window {
                // `ok_or(&str)?` works, because From<&str> is implemented for Box<dyn Error>
                title: self.window_title.take().ok_or("window_title is unset")?,
                dimensions: self
                    .window_dimensions
                    .take()
                    .ok_or("window_dimensions are unset")?,
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        let mut builder = GameBuilder::new();
        builder.window_title("Awesome Builder");
        builder.window_dimensions(800, 600);
        let game = builder.build();

        assert_eq!(
            game.expect("build success"),
            Game {
                window: Window {
                    title: "Awesome Builder".into(),
                    dimensions: (800, 600)
                }
            }
        );
    }

    #[test]
    fn test_1() {
        let game2 = GameBuilder::new()
            .window_title("Busy Builder")
            .window_dimensions(1234, 123)
            .build();

        assert_eq!(
            game2.expect("build success"),
            Game {
                window: Window {
                    title: "Busy Builder".into(),
                    dimensions: (1234, 123),
                }
            }
        )
    }
}
于 2021-09-13T19:48:56.817 回答