Game of Life - Rust

fn populate_to_file(filename: impl AsRef<std::path::Path>, world: [[u8; 75]; 75]) {
    use std::iter::Iterator;
    use std::io::Write;
    let mut file = std::fs::File::create(filename).expect("Failed to create file!");
    for (i, row) in world.into_iter().enumerate() {
        for (j, _) in row.into_iter().enumerate().filter(|(_, cell)| cell==1) {
            write!(file, "{} {}\n", i, j).expect("Failed to write to file!");
        }
    }
}

I tried the above answer and I get the following error ^^ no implementation for '&&u8 == {integer}' The IDE says that the trait PartialEq<(Integer)>' is not implemented for '&&u8'.

Please help.

Rust is very strict about typing: in particular, you must usually be explicit about what is a reference and what is a value.
In particular, in your particular example, cell has type &&u8, because:

  • into_iter on [u8; 75] yields &u8 (for now :stuck_out_tongue:)
  • filter adds another reference

So you need to either:

  • dereference cell twice: **cell == 1
  • borrow 1 twice: cell == &&1
  • *cell == &1
  • etc...

Note that filter's documentation talks about this: documentation in std is nicely explicit about these pitfalls :wink:

4 Likes

BTW, use BufWriter, otherwise writing will be quite slow, since every single write! will actually update the file.

3 Likes

Thanks for the help. I changed the code and simplified it and it worked.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.