RUST Documentation 따라 공부하기 2
2019.12.30
Programming a Guessing Game
- 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);
}
use std::io;
to obtain user input and then print the result as output, we need to bring the io library into scope.
let mut guess
In RUST, variables are immutable by default.
String::new()
how to call static method in RUST.
&
RUST has reference.
Handling potential failure with the
Result
typeAs 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, anio::Result
. Rust has a number of types namedResult
in its standard library: a genericResult
as well as specific versions for submodules, such asio::Result
.Result
types are enumerations. ForResult
the variats areOk
orErr
.Err
contaions information about why the operation failed.If I don't call
.expect
, the program will compile, but I'll get a warning.Printing values with
println!
placeholders
Generating a secret number
crate
is a collection of Rust code files.
- 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.
- 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 방식을 지향한다.
- number types
i32 : 32-bit number / i64 : 64-bit number
u32 : unsigned 32-bit number
Rust defaults to an i32.
- 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인, Ok
와 Err
를 사용하여 위와 같이 하면, 올바른 값을 parsing 할 수 있을 경우에 해당 값을 return하여 guess에 담는다.