Rust

RUST Documentation 따라 공부하기 2

2019.12.30


Programming a Guessing Game

  1. guessing_game
use std::io;

fn main() {
    println!("Guess the number!");

    println!("Please input your guess.");

    let mut guess = String::new();
    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");

    println!("You guessed: {}", guess);
}
  1. use std::io;

    to obtain user input and then print the result as output, we need to bring the io library into scope.

  2. let mut guess

    In RUST, variables are immutable by default.

  3. String::new()

    how to call static method in RUST.

  4. &

    RUST has reference.

  5. Handling potential failure with the Result type

    As mentioned earlier, read_line puts what the user types into the string we’re passing it, but it also returns a value—in this case, an io::Result. Rust has a number of types named Result in its standard library: a generic Result as well as specific versions for submodules, such as io::Result.

    Result types are enumerations. For Result the variats are Ok or Err. Err contaions information about why the operation failed.

    If I don't call .expect, the program will compile, but I'll get a warning.

  6. Printing values with println! placeholders

Generating a secret number

crate is a collection of Rust code files.

  1. modify Cargo.toml : add rand crate
...
[dependencies]
rand = "0.3.14"
cargo build
# install libraries from crates.io
# Cargo.lock 파일에 적절한 version의 dependency가 깔린다.
# Q. Cargo.toml 파일은 그럼 어쩌지..?

cargo update

cargo doc --open
# 현재 사용하고 있는 라이브러리에 대하여 document를 볼 수 있다...
  • Crates.io : where people in Rust ecosystem post their open source Rust projects.
  1. shadowing
fn main() {
  let mut test = String::new();
  io::stdin().read_line(&mut test)
  .expect("Failed to read");
  let test: u32 = test.trim().parse().expect("please type a number");
}

test라는 변수명을 사용했는데, 또 사용해도 되나?

Rust에서는 변수의 타입을 변경할 때, shadowing 방식을 지향한다.

  1. number types

​ i32 : 32-bit number / i64 : 64-bit number

​ u32 : unsigned 32-bit number

​ Rust defaults to an i32.

  1. error handling
let mut guess = String::new();
io::stdin()
  .read_line(&mut guess)
  .expect("Failed to read line");

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

expect 에서 match로 바꾸면 이렇게 된다.

Result 타입에 있는 enum인, OkErr 를 사용하여 위와 같이 하면, 올바른 값을 parsing 할 수 있을 경우에 해당 값을 return하여 guess에 담는다.