Learn variables and data types through simple examples in Rust.

Example 1: Simple Variables Example

This example project will teach you the following concepts:

  1. let keyword in rust
  2. Variables in rust

Step 1: Create Project

The first step is to create a Rust project. We can use Cargo to generate us a project template. Use the following command:

cargo new your_project_name

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Create a file named main.rs and inside it create a main function:

fn main() {

The let keyword introduces a local variable. Variables are immutable by default.To introduce a local variable that you can re-assign later, use let mut instead.

    let hi = "hi";
    let mut count = 0;

    while count < 10 {
        println!("{}, count: {}", hi, count);
        count += 1;
    }

Although Rust can almost always infer the types of local variables, you can specify a variable's type by following it in the let with a colon, then the type name. Static items, on the other hand, always require a type annotation.

    static MONSTER_FACTOR: f64 = 57.8;
    let monster_size = MONSTER_FACTOR * 10.0;
    println!("{}", monster_size);
    let monster_size = 50;
    println!("{}", monster_size);

Syntax extensions:

    // {} will print the "default format" of a type
    println!("{} is {}", "the answer", 43);

    // // {:?} will conveniently print any type
    println!("what is this thing: {:?}", monster_size);
}

Here is the full code:

main.rs

fn main() {

    let hi = "hi";
    let mut count = 0;

    while count < 10 {
        println!("{}, count: {}", hi, count);
        count += 1;
    }

    static MONSTER_FACTOR: f64 = 57.8;
    let monster_size = MONSTER_FACTOR * 10.0;
    println!("{}", monster_size);
    let monster_size = 50;
    println!("{}", monster_size);
    println!("{} is {}", "the answer", 43);
    println!("what is this thing: {:?}", monster_size);
}

If you run the code you will get the following:

hi, count: 0
hi, count: 1
hi, count: 2
hi, count: 3
hi, count: 4
hi, count: 5
hi, count: 6
hi, count: 7
hi, count: 8
hi, count: 9
578
50
the answer is 43
what is this thing: 50

Run

Save the code and run your code as follows using Cargo:

$ cargo run

Example 2: Rust Variables Examples

Simple variables usage in Rust with explanations.

Step 1: Create Project

The first step is to create a Rust project. We can use Cargo to generate us a project template. Use the following command:

cargo new your_project_name

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Here's the commented code:

main.rs

fn main() {
    let x = 5;
    println!("x: {}", x);

    // x variable is immutable.
    // so we can't change its value.
    // x = 6;

    // but we can declare a new variable,
    // with the same name: x.
    //
    // this way, we don't need to imagine
    // new variable names.
    let x = 6;
    println!("x: {}", x);

    // we can also create a constant.
    // constant are compile-time values.
    // so, anywhere MAX_VALUE appears, the
    // compiler will change it with 10 instead.
    //
    // instead of using hardcoded values, use
    // constants instead.
    const MAX_VALUE: u32 = 10;
    println!("MAX_VALUE: {}", MAX_VALUE);

    // SHADOWING
    let spaces = "   ";        // &str
    let spaces = spaces.len(); // usize
    println!("spaces: {}", spaces);
}

Step 4: Run

Save the code and run your code as follows using Cargo:

$ cargo run

Result

Here's what you get:

x: 5
x: 6
MAX_VALUE: 10
spaces: 3

Example 3: Rust Data Types

Learn Data types in Rust using this simple well commented example.

Step 1: Create Project

The first step is to create a Rust project. We can use Cargo to generate us a project template. Use the following command:

cargo new your_project_name

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Here's the code:

main.rs

fn main() {
    // err: parse cannot know the type of guess.
    // let guess = "42".parse().expect("Not a number!");

    // here, we tell rust that guess is an u32 variable.
    let guess: u32 = "42".parse().expect("Not a number!");
    println!("{}", guess);

    // ====================================================
    // SCALAR TYPES
    // Represent a single value.
    // ====================================================

    // INTEGERS:
    // i8 to i128 and u8 to u128
    // -> i means signed integer
    // -> u means unsigned integer

    // there are also:
    // isize and usize.
    //
    // rust determines their sizes depending on the
    // computer the compiler runs
    //
    // for example:
    // on a 64-bit computer: isize is i64 and usize is u64.
    // on a 32-bit computer: isize is i32 and usize is u32.

    // INTEGER LITERALS:
    let _ = 1_2_3; // decimal
    let _: i64 = 0xdeadbeef; // hex
    let _ = 0o444; // octal
    let _ = 0b0101_1010; // binary
    let _ = b'I'; // byte

    // run with: cargo r -q --release
    // to see the wrapping behavior.
    //
    // 255 + 1 becomes 0.
    // 1111_1111 + 1 = 0000_0000

    // let mut over: u8 = 255;
    // over += 1;
    // println!("over: {}", over);

    let _ = 2.0; // f64
    let _: f32 = 3.0; // f32
    let _ = true || false; // bool
    let _ = '💯'; // char

    // TUPLES
    let point = (10, 20.5);
    let (x, y) = point;
    println!("x: {}, y: {}", x, y);
    println!("x: {}, y: {}", point.0, point.1);

    // ARRAYS
    let days = ["Monday", "Tuesday", "Wednesday", "Thursday",
        "Friday", "Saturday", "Sunday"];
    println!("days: {}", days.join(", "));

    // each element's type is i64
    // and there are 5 elements.
    let _: [i64; 5] = [1, 2, 3, 4, 5];

    // 3 elements, each one is 1: [1, 1, 1]
    let _ = [1; 3];

    hello();
    say(10, 20);

    // {...} is an expression.
    let (x, y) = {
        let x = 1;
        (x + 1, 5) // <- here it returns a tuple: (2, 5)
    };
    say(x, y);
    say(one().0, one().1);
}

fn hello() {
    println!("hello!");
}

fn say(n: i32, m: i64) {
    println!("n: {}, m: {}", n, m);
}

fn one() -> (i32, i64) {
    (1, 2)
}

Run

Save the code and run your code as follows using Cargo:

$ cargo run

Result

Here's what you get:

42
x: 10, y: 20.5
x: 10, y: 20.5
days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
hello!
n: 10, m: 20