After reading Rust book chapter 3

rust

Variables and Mutability

(1) let

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}


(2) constants

const MAX_POINTS: u32 = 100_000;


Shadowing

fn main() {
    let x = 5;

    let x = x + 1;

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

    println!("The value of x is: {}", x);
}
// O
let spaces = "   ";
let spaces = spaces.len();

// X (mismatched types)
let mut spaces = "   ";
spaces = spaces.len();



Data Types

let guess: u32 = "42".parse().expect("Not a number!");

: 문자열을 숫자 타입으로 변환할 때처럼 여러 타입을 사용해야 한다면 type annotation을 통해 타입을 명시한다.


(1) 스칼라(Scarlar) 타입

(2) 컴파운드(Compound) 타입


튜플

fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    let (x, y, z) = tup;

    println!("The value of y is: {}", y);
}
fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);

    let five_hundred = x.0;

    let six_point_four = x.1;

    let one = x.2;
}


배열

fn main() {
    let a = [1, 2, 3, 4, 5];

    let b: [i32; 5] = [1, 2, 3, 4, 5];
}



함수

fn main() {
    println!("Hello, world!");

    another_function();

    // statement
    let y = 6;

    // expressions
    let y2 = {
        let x = 3;
        x + 1
    };
}

fn another_function() {
    println!("Another function.");
}

// arrow function
fn five() -> i32 {
    5
}



Control Flow

(1) if

// Handling Multiple Conditions
fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
}

// Using in a let Statement
fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };

    println!("The value of number is: {}", number);
}


(2) loop, while, for

fn main() {
    // loop
    let mut counter = 0;
    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result);

    // while
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index += 1;
    }

    // for
    for element in a {
        println!("the value is: {}", element);
    }

    for number in (1..4).rev() {
        println!("{}!", number);
    }
}