Values and variables

Print things, and give values names so you can use them again.

Your Rust code runs inside your browser tab. Nothing to install.

Printing a value

A program is a list of instructions that run from top to bottom.

A Rust program starts at a function called main. println! prints a line. To print a value that is not plain text, put {} in the quotes where the value should go, and the value after a comma.

Load the example and press Run. The first run downloads the Rust compiler, about 90 MB, and can take a minute. Your browser keeps it for next time. Each run takes several seconds, because Rust is compiled for real.

Example
fn main() {
    println!("Hello");
    println!("{}", 42);
}

Naming a value

A variable is a name for a value.

let creates a variable. Rust works out the kind of value for itself. A variable cannot be changed later unless it is created with let mut.

After that, the name can be used wherever the value is needed.

Example
fn main() {
    let name = "Asha";
    let marks = 82;
    println!("{}", name);
    println!("{}", marks + 5);
}

Your turn: a variable

Create a variable and print it.

Practice task

Create a variable called `city` holding the text Pune, then print it.

Your answer is run and checked in the lesson. Try it now.

Working with numbers

Numbers can be added with +, subtracted with -, multiplied with * and divided with /.

Dividing one whole number by another gives a whole number and drops the remainder.

Multiplying and dividing happen before adding and subtracting. Use brackets to change the order.

Example
fn main() {
    let price = 250;
    let quantity = 3;
    let total = price * quantity;
    println!("{}", total);
    println!("{}", (total + 50) / 2);
}

Your turn: a calculation

Three subjects were marked 82, 67 and 91.

Practice task

Store the three marks 82, 67 and 91 in variables, then print their average: the sum divided by 3.

Your answer is run and checked in the lesson. Try it now.