Exercise: Variables

In the last exercise we saw lots of ways to print, but to be fair, using placeholders doesn’t make much sense if we have to write what goes inside, right?

So in this one we’ll explore how to combine the previous things we learned with variables.

First things first, we’ll create a new program again. This time we will call it variables.rs.

So go ahead and create it in the folder learnrust/src/bin/.

As usual, we will start with fn main() {}:

fn main() {

}

Now go to Cargo.toml and add:

[[bin]]
name = "variables"

Test that it works by running:

$ cargo run --bin variables

Hello, Waldo!

Let’s try a variation of the mythical “Hello, World!” program:


#![allow(unused)]
fn main() {
    let name = "Waldo";
    println!("Hello, {}!", name);
}

And we can try a few variables with numbers and math:


#![allow(unused)]
fn main() {
    let a = 3;
    let b = 7;
    let c = a * b;
    println!("The result of {} * {} is {}", a, b, c);
}

Let’s try to mutate one variable over and over:


#![allow(unused)]
fn main() {
    let mut x = 4;
    let a = 3;
    println!("{}", x);
    x = 6;
    println!("{}", x);
    x = 1 + a;
    println!("{}", x);
}

We can also do operations with variables:


#![allow(unused)]
fn main() {
    let x = 4;
    let a = 3;
    println!("{} + {} = {}", x, a, x + a);
}

HINT: Remember you have the play button/icon on each code block to execute these samples in your browser.

Done!

Here’s the full program:

fn main() {
    let name = "Waldo";
    println!("Hello, {}!", name);

    let a = 3;
    let b = 7;
    let c = a * b;
    println!("The result of {} * {} is {}", a, b, c);

    let mut x = 4;
    let a = 3;
    println!("{}", x);
    x = 6;
    println!("{}", x);
    x = 1 + a;
    println!("{}", x);

    let x = 4;
    let a = 3;
    println!("{} + {} = {}", x, a, x + a);
}

The output is:

Hello, Waldo!
The result of 3 * 7 is 21
4
6
4
4 + 3 = 7