Skip to content

Latest commit

 

History

History
44 lines (32 loc) · 996 Bytes

README.md

File metadata and controls

44 lines (32 loc) · 996 Bytes

Programming a Guessing Game1

To run the program:

$ cargo run --bin guessing-game
   Compiling guessing-game v0.1.0 ...

Lessons learned

  • Sometimes (extern crate rand) you just need stack overflow.

  • A String is both an immutable and mutable buffer of characters.

  • You create a new mutable variable with let mut:

    let mut guess = String::new();
  • And read into it as a reference, i.e. &mut guess:

    io::stdin().read_line(&mut guess);
  • Many Rust APIs return enums, such as Result. You can use .expect to panic:

    result.expect("Failed to read line");
  • Or (pattern) match against the result, such as:

    let guess:u32 = match guess.parse() {
      Ok(num) => num,
      Err(_) => {
        println!("Invalid!");
        continue;
      }
    }

Footnotes

  1. Source: https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html