Rust practice (guessing game)

codernineteen·2022년 1월 14일
0

Rust dev

목록 보기
2/4
post-thumbnail

Traditional guessing game with Rust language


Code 1

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);
}

Let's break this code line by line.

  1. use std::io;
    To get user input and give output, we need use 'io'(input/output)
    'io' comes from standart library 'std'
  • prelude type : std brings into the scope of every program
  • no prelude type : use 'use' keyword and std::'library name'
  1. fn main() {}
    As you know, main is entry point.
    you can put parameter in ()

  2. println!();
    Rust macro to prints a string on screen

  3. let mut guess = String::new();
    To assign value to variable, In Rust, you can use 'let' keyword.
    Rust varibale is immutable by default.(like javascript const)
    If you want mutate a variable, you should add 'mut' keyword.
    'guess' is variable name.
    'String::new()' is a value. String is a string type.
    :: syntax indicates 'new' is an associated function of String type.
    An associated function is a function that's implemented on a type.
    In here, a 'new' function creates a new string.

io::stdin()
	.read_line(&mut guess)

'stdin' is a function that returns an instance of 'std::io::Stdin'(a type that represents a handle to the standard input for your terminal)

  1. .read_line(&mut guess)
    Its role is take whatever the user types in input and append that into a string. Also string argument should be 'mut' to change the content.
    '&' points that this argument is a reference

  2. .expect("Failed to read line");
    read_line returns a value (io::Result in above case).
    A Reuslt type is are enumerations. It means its variants are 'Ok' or 'Err'.
    Values of the 'Result' type have methods defined on them. That's why we can use .expect() after read_line().
    If io::Result is an Ok value, 'expect' will take the return value that ok is holding.

  3. println!("You guessed: {}", guess);
    You can print dynamic string with curly brackets.
    Variable order which will be applied into curly brackets is from start to end
    println!("x = {} and y = {}", x, y);

Code 2

To create random number for guessing num, we need to use library.
There is rand crate which is a library crate. This can be used for other programs.
In Cargo.toml, add dependecies which you want to add your project.
In this case,

[dependencies]
rand = "0.8.3"

There is so many libraries in crates.io

Rust offical docs

use std::io;
use rand::Rng;

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

    let secret_number = rand::thread_rng().gen_range(1,..101);

    println!("The secret number is {}", secret_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 rand::Rng;
    Rng trait defines methods that random number generators implement.\

  2. let secret_number = rand::thread_rng().gen_range(1,..101);
    These methods are defined by the Rng trait

Code 3

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    // omitted

    println!("You guessed: {}", guess);

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => println!("You win!"),
    }
}
  1. use std::cmp::Ordering;
    This line bring above type into scope from std.
    Ordering type is another enum(Less, Greater, and Equal)
    'cmp' method compares two values and can be called on anything can be compared.

  2. match
    we use 'match' expression. It's comparing guess to the secret_number, then it returns variants of Ordering.

Code 4

Rust has strong , static type system. So if you compare string to number, it occurs 'mismatched' errors.
So add this line to convert type.
let guess: u32 = guess.trim().parse().expect("Please type a number!");
Rather than create new variable for different type, you can override variable in Rust

Final code

use std::io;
use std::cmp::Ordering;
use rand::Rng;

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

    loop {
        let secret_number = rand::thread_rng().gen_range(1..101);

        println!("The secret number is {}", secret_number);

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

        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,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            },
        }
    }
}
profile
슈퍼 주니어 개발자

0개의 댓글