Rust Programming By Example
上QQ阅读APP看书,第一时间看更新

Saving/loading high scores

To keep things simple, we'll have a very simple file format:

  • On the first line, we store the best scores
  • On the second line, we store the highest number of lines

Let's start by writing the save function:

    fn slice_to_string(slice: &[u32]) -> String {
      slice.iter().map(|highscore| highscore.to_string()).
collect::<Vec<String>>().join(" ") } fn save_highscores_and_lines(highscores: &[u32],
number_of_lines: &[u32]) -> bool { let s_highscores = slice_to_string(highscores); let s_number_of_lines = slice_to_string(number_of_lines); write_into_file(format!("{}\n{}\n", s_highscores,
s_number_of_lines)).is_ok() }

It was a small lie: there are actually two functions. The first one is just here to make the code smaller and easier to read even though we need to explain what it does, because we're about to talk about a big feature from Rust—iterators!