-5

This source code is an excerpt of a function which simulates the Game of Life. I'm trying to write the contents of the game grid to a file.

fn populate_to_file(filename: &String, world: [[u8; 75]; 75]) {
    let path = std::fs::File::create(filename);

    for i in 0..74 {
        for j in 0..74 {
            if world[i][j] == 1 {
                let x_str = String::from(i.to_string());
                let y_str = String::from(j.to_string());
                fs::write(filename, x_str + &" ".to_string()).expect("Failed to write to file!");
                fs::write(filename, y_str).expect("Failed to write to file!");
            }
        }
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mark King
  • 1
  • 2
  • 3
    Read the documentation for `std::fs::write` again. Also pay attention to what `std::fs::File::create` actually returns. – Colonel Thirty Two Jul 13 '21 at 14:02
  • 3
    [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) – Shepmaster Jul 13 '21 at 14:07
  • 1
    Please [edit] your question and paste the exact and entire error that you're getting — that will help us to understand what the problem is so we can help best. Sometimes trying to interpret an error message is tricky and it's actually a different part of the error message that's important. Please use the message from running the compiler directly, not the message produced by an IDE, which might be trying to interpret the error for you. – Shepmaster Jul 13 '21 at 14:07
  • 1
    Note that `0..74` **excludes** the `74`. This means you are losing one row and column. It's better to iterate directly over the data (like `for i in &world`), potentially also using `Iterator::enumerate`. – Shepmaster Jul 13 '21 at 14:09
  • "This function will create a file if it does not exist, and will entirely replace its contents if it does." – CodesInChaos Jul 14 '21 at 15:35

1 Answers1

0
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!");
        }
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
mmirate
  • 704
  • 6
  • 25
  • While this might solve the question, an explanation on *how* / *why* it solves it would help, including why `std::fs::write` is the wrong tool in this scenario, as well as explaining why `filename`'s type changed, and why you're using iterators instead of indexing – Filipe Rodrigues Jun 01 '22 at 19:57
  • Stop rolling back. The text adds no value to the post. If you believe the question should be closed, flag it instead – Zoe Jul 12 '22 at 17:37