Tutorials

RUST

After a long while I decided to dive deeper into RUST. I was around in the early days of RUST at Mozilla so it has been a long time on my to-do list. I started with the most obvious choice and that is the RUST book The Rust Programming Language – The Rust Programming Language (rust-lang.org) and slowly working my way through them with the aim to have it completed across this summer.

Creating the guessing game early on was a great way to get you coding early on and give you a nice simple piece of code to hack around with.

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

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

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

    loop {

        println!("Please enter the number that you guessed?");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read number");

        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 guessed right! You Win");
                break;
            }
        }

    }
}

I have been enjoying the syntax and really loving CARGO and tools such as cargo fix and cargo fmt.

I have been using sublime for my text editor and found GitHub – rust-lang/rust-enhanced: The official Sublime Text 3 package for the Rust Programming Language very helpful package.

I also suggest playing around more with Cargo and getting to know it better Cargo Build System – Rust Enhanced User Guide (rust-lang.github.io)

RUST Data Types code examples from Chapter Three in the RUST book

fn main() {
    const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
    const WORDS: &str = "hello convenience!";
    let mut x = 5;
    println!("The value of x is: {x}");
    x = 6;
    println!("The value of x is: {x}");
    let foo = THREE_HOURS_IN_SECONDS + 20;
    println!("{foo}");

    let y = 5;

    let y = y+1;
    {
        let y = y * 2;
        println!("The value of y in the inner scope is: {y}");
    }

    println!("The value of y in the inner scope is: {x}");
    println!("{WORDS}");

}