CourseLesson 3 · Variables, Types and FunctionsSolve

Lesson 03

Variables, Types and Functions

Goal

By the end of this lesson you will be able to:

  1. Declare a variable with let, and change it with mut.

  2. Explain what shadowing does and how it differs from mut.

  3. Declare a constant with const.

  4. Print any value with println!, including its bits.

  5. Name the scalar types and choose one for a value.

  6. Do arithmetic, and say what happens when a result does not fit.

  7. Convert a value from one type to another with as.

  8. Group values in a tuple and in an array, and read them back.

  9. Write a function with parameters and a return value.

Every program in this lesson can be typed into src/main.rs of a cargo project and run with cargo run. Do that for each one, and change a line or two to see what happens.

Variables

Declaring a Variable with let

let creates a variable and gives it a value.

fn main() {
    let count = 5;
    let price = 2.5;
    let name = "Asha";

    println!("{count} {price} {name}");
}
5 2.5 Asha

Every variable has a type. You did not write one here, and the compiler worked each type out from the value on the right. This is called type inference. A whole number with nothing else to decide it is an i32. A number with a decimal point is an f64. Text in double quotes is a &str, read as “a piece of text”.

You can write the type yourself, after a colon. Do this when you want a different type from the one the compiler would pick, or when you want the type to be visible to whoever reads the program.

let count: u8 = 5;
let price: f32 = 2.5;

Variable names are written in small letters, with an underscore between words: count, page_count, is_ready. The compiler accepts other spellings, but every Rust program you read uses this one.

Variables Do Not Change by Default

A variable made with let keeps its first value. Assigning a second value is a compile error.

fn main() {
    let count = 5;
    println!("{count}");
    count = 6;
    println!("{count}");
}
error[E0384]: cannot assign twice to immutable variable `count`
 --> src/main.rs:4:5
  |
2 |     let count = 5;
  |         ----- first assignment to `count`
3 |     println!("{count}");
4 |     count = 6;
  |     ^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut count = 5;
  |         +++

The word immutable means “cannot be changed”. Most variables in a program are set once and read many times. Making that the default means the compiler can tell you when a value changes somewhere you did not expect it to.

Changing a Variable with mut

Write mut after let when the variable has to change.

fn main() {
    let mut count = 5;
    println!("{count}");

    count = 6;
    println!("{count}");

    count += 10;
    println!("{count}");
}
5
6
16

count += 10 adds 10 to count and stores the result back in count. It is short for count = count + 10. Every arithmetic operator has this short form: -=, *=, /= and %= work the same way.

A mut variable can change its value, but never its type. It was declared as an i32, so it stays an i32.

Shadowing

A second let with the same name makes a new variable. The old one is hidden from that line on. This is called shadowing.

fn main() {
    let spaces = "   ";
    let spaces = spaces.len();

    println!("{spaces}");
}
3

The first spaces is a piece of text. The second is a number: the length of that text. That is allowed, because the second let makes a new variable, and a new variable can have any type. mut cannot do this.

fn main() {
    let mut spaces = "   ";
    spaces = spaces.len();

    println!("{spaces}");
}
error[E0308]: mismatched types
 --> src/main.rs:3:14
  |
2 |     let mut spaces = "   ";
  |                      ----- expected due to this value
3 |     spaces = spaces.len();
  |              ^^^^^^^^^^^^ expected `&str`, found `usize`

A shadow lasts until the end of the block it was made in. When the block ends, the old variable is visible again.

fn main() {
    let x = 5;
    let x = x + 1;

    {
        let x = x * 2;
        println!("inside: {x}");
    }

    println!("outside: {x}");
}
inside: 12
outside: 6

mut Changes a Value, let Makes a New Variable

count += 1 writes a new value into the same variable. let count = count + 1 makes a second variable that happens to have the same name. Use mut for a value that changes as the program runs. Use shadowing to turn a value into a different form, such as text into a number, and keep the same name for it.

Constants

A constant is a value that is fixed for the whole program. Declare it with const, give it a type, and write its name in capital letters.

const MAX_MARK: u32 = 100;

fn main() {
    println!("{MAX_MARK}");
    println!("{}", MAX_MARK * 2);
}
100
200

A constant differs from a let variable in three ways. The type is always written: const MAX_MARK = 100; does not compile. The value must be one the compiler can work out before the program runs, so it cannot come from the user. And a constant can be declared outside every function, at the top of the file, where every function can use it.

Unused Variables

The compiler warns you about a variable that is never read.

fn main() {
    let count = 5;
    println!("done");
}
warning: unused variable: `count`
 --> src/main.rs:2:9
  |
2 |     let count = 5;
  |         ^^^^^ help: if this is intentional, prefix it with an underscore: `_count`
  |
  = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default

done

A warning does not stop the build: the program still ran and printed done. It points at a variable you probably forgot to use, or a name you misspelt further down. If the variable is unused on purpose, start its name with an underscore, and the warning goes away.

Printing with println!

println! prints one line. The text in quotes is printed as it is, except for the parts in braces, which are replaced by values.

fn main() {
    let name = "Asha";
    let mark = 71;

    println!("{} scored {}", name, mark);
    println!("{name} scored {mark}");
}
Asha scored 71
Asha scored 71

Both lines print the same thing. An empty pair of braces {} takes the next value from the list after the text, in order. A name inside the braces takes that variable directly. Only a plain variable name can go inside the braces, so use the name when you print a variable, and the empty braces when you print the result of a calculation, as in println!("{}", mark * 2).

A colon inside the braces adds instructions on how to print the value.

fn main() {
    let mark = 71;
    let ratio = 2.0 / 3.0;
    let pair = (1, 2);

    println!("{ratio:.2}");
    println!("[{mark:>6}]");
    println!("[{mark:06}]");
    println!("{mark:b}");
    println!("{mark:08b}");
    println!("{pair:?}");
}
0.67
[    71]
[000071]
1000111
01000111
(1, 2)
Inside the bracesWhat it prints
{ratio:.2}the number rounded to 2 decimal places
{mark:>6}the value pushed to the right end of a 6-character space
{mark:06}the value in 6 characters, filled with zeros
{mark:b}the value in binary
{mark:08b}the value in binary, 8 bits wide, filled with zeros
{pair:?}a value that has no plain printed form, such as a tuple

{mark:08b} is the row to remember. It shows you the bits of any integer, so you can check what a bitwise operation did.

Scalar Types

A scalar type holds one value. Rust has four kinds of scalar type: integers, floating point numbers, bool and char.

Integers

An integer is a whole number. The name of the type says its sign and its width: u for unsigned (zero and up), i for signed (negative numbers too), then the width in bits.

WidthSignedUnsigned
8 bitsi8u8
16 bitsi16u16
32 bitsi32u32
64 bitsi64u64
128 bitsi128u128
the width of an addressisizeusize

i32 is the type the compiler picks for a whole number when nothing else decides it. It is a good first choice for most counting and arithmetic.

usize is the type for a size or a position: how many items there are, or which item you mean. Its width is the width of a memory address on the machine the program runs on, which is 64 bits on every current desktop and laptop computer. When you ask an array how long it is, the answer is a usize. When you ask for the item at a position, the position must be a usize.

A number can be written with underscores to make it easier to read, in binary with 0b in front, or with its type as a suffix.

let big = 1_000_000;        // an i32, the same as 1000000
let bits = 0b0000_0101;     // an i32 holding 5
let small = 5u8;            // a u8 holding 5

Arithmetic

The five arithmetic operators are +, -, *, / and %.

fn main() {
    println!("{}", 7 + 2);
    println!("{}", 7 - 2);
    println!("{}", 7 * 2);
    println!("{}", 7 / 2);
    println!("{}", 7 % 2);
    println!("{}", -7 / 2);
    println!("{}", -7 % 2);
}
9
5
14
3
1
-3
-1

Two of these rows need extra explanation. 7 / 2 is 3, not 3.5. When both sides are integers, the result is an integer, and the part after the decimal point is thrown away. % gives the remainder of that division: 7 divided by 2 is 3 with 1 left over, so 7 % 2 is 1. A negative number divides towards zero, so -7 / 2 is −3-3, and the remainder keeps the sign of the left side.

% is the usual way to test whether a number is even: n % 2 is 0 for an even number and 1 for an odd one.

Overflow

Every integer type has a largest value. A u8 stops at 255. Adding 1 to 255 in a u8 needs a ninth bit, and there is no ninth bit. This is called overflow.

When the compiler can see the overflow, it refuses to build the program.

fn main() {
    let x: u8 = 255;
    let y = x + 1;
    println!("{y}");
}
error: this arithmetic operation will overflow
 --> src/main.rs:3:13
  |
3 |     let y = x + 1;
  |             ^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow

Usually the compiler cannot see it, because the value comes from the user or from a calculation. Then the program stops when the overflow happens.

fn add_one(n: u8) -> u8 {
    n + 1
}

fn main() {
    println!("{}", add_one(254));
    println!("{}", add_one(255));
}
255

thread 'main' (1302688) panicked at src/main.rs:2:5:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

add_one is a function. It takes one u8, adds 1 to it, and gives the result back. The first call worked. The second overflowed, and the program stopped with a message instead of printing a wrong answer. Stopping like this is called a panic.

This check is only in the development build that cargo run makes. In a release build, made with cargo run -{}-release, the check is left out for speed, and the value wraps round: 255 plus 1 gives 0. If you want the wrap, say so: x.wrapping_add(1) gives 0 in every build and never panics. u8::MAX is the largest u8, 255, and every integer type has a MAX and a MIN like it.

Floating Point Numbers

A floating point number has a decimal part. There are two types: f32, 32 bits wide, and f64, 64 bits wide. A number written with a decimal point is an f64 unless you say otherwise. An f64 holds about 15 significant digits and an f32 about 7, so use f64 unless memory is short.

fn main() {
    let half = 7.0 / 2.0;
    let third: f64 = 1.0 / 3.0;
    let rough: f32 = 1.0 / 3.0;

    println!("{half}");
    println!("{third}");
    println!("{rough}");
    println!("{third:.2}");
    println!("{}", 0.1 + 0.2);
}
3.5
0.3333333333333333
0.33333334
0.33
0.30000000000000004

7.0 / 2.0 is 3.5, because both sides are floating point. The same division on integers, 7 / 2, is 3.

The last line is not a mistake in Rust. A floating point number is stored in binary, and 0.1 cannot be written exactly in binary, in the same way that a third cannot be written exactly in decimal. The stored value is very close to 0.1 but not equal to it, and the small differences add up. Two rules follow from this. Print a floating point number with a fixed number of decimal places, as {third:.2} does. And never test two floating point numbers for equality with ==: test whether their difference is small.

Mixing Types

Rust never converts a number from one type to another on its own. An integer and a floating point number cannot be multiplied together, and neither can two integers of different widths.

fn main() {
    let count = 5;
    let price = 2.0;
    println!("{}", count * price);
}
error[E0277]: cannot multiply `{integer}` by `{float}`
 --> src/main.rs:4:26
  |
4 |     println!("{}", count * price);
  |                          ^ no implementation for `{integer} * {float}`
fn main() {
    let small: u8 = 5;
    let big: u32 = 10;
    println!("{}", small + big);
}
error[E0308]: mismatched types
 --> src/main.rs:4:28
  |
4 |     println!("{}", small + big);
  |                            ^^^ expected `u8`, found `u32`

In C, the compiler would quietly widen the u8 and carry on. Rust makes you say what you want, because the two directions give different answers when a value does not fit.

Converting with as

as converts a value to another type. Write the value, then as, then the type you want.

fn main() {
    let small: u8 = 5;
    let big: u32 = 10;
    println!("{}", small as u32 + big);

    let wide: u16 = 300;
    println!("{}", wide as u8);

    let neg: i8 = -1;
    println!("{}", neg as u8);

    println!("{}", 3.99 as i32);
    println!("{}", -3.99 as i32);

    let n: i32 = 7;
    println!("{}", n as f64 / 2.0);
}
15
44
255
3
-3
3.5

Converting to a wider type keeps the value: small as u32 is still 5. Converting to a narrower type keeps only the bits that fit. 300 as a u16 is 0000 0001 0010 1100. A u8 keeps the low eight bits, 0010 1100, which is 44. The ninth bit is gone, and no error is reported.

Converting a negative number to an unsigned type keeps the bits and reads them without a sign: −1-1 as an i8 is 1111 1111, and the same bits as a u8 are 255. Converting a floating point number to an integer throws the decimal part away, in both directions: 3.99 becomes 3 and −3.99-3.99 becomes −3-3. Converting an integer to f64 is the safe direction, and it is how you divide two integers and keep the decimal part.

as Never Complains

as always compiles and never panics. It gives you the bits that fit and throws the rest away. Before you narrow a value, ask whether it can ever be larger than the new type holds.

char

A char is one character, written between single quotes. It can be any character in any language, not only a letter of the English alphabet, so it takes four bytes.

fn main() {
    let letter = 'A';
    let accented = 'é';

    println!("{letter} {accented}");
    println!("{}", letter as u8);
    println!("{}", 97u8 as char);
}
A é
65
a

Every character has a number. 'A' is 65 and 'a' is 97, and as converts between the character and its number.

Single quotes and double quotes make different types. 'A' is a char: one character. "A" is a &str: a piece of text that happens to be one character long. They are not interchangeable.

fn main() {
    let letter: char = "A";
    println!("{letter}");
}
error[E0308]: mismatched types
 --> src/main.rs:2:24
  |
2 |     let letter: char = "A";
  |                 ----   ^^^ expected `char`, found `&str`
  |                 |
  |                 expected due to this
  |
help: if you meant to write a `char` literal, use single quotes
  |
2 -     let letter: char = "A";
2 +     let letter: char = 'A';

bool

A bool is true or false. It takes one byte. Every comparison produces one: 10 > 3 is true.

Compound Types

A compound type holds several values in one. Rust has two built in: the tuple and the array.

Tuples

A tuple groups a fixed number of values, which may have different types, in a fixed order. Write the values between parentheses.

fn main() {
    let reading = ("Pune", 31, 2.5);

    println!("{}", reading.0);
    println!("{}", reading.1);
    println!("{}", reading.2);
    println!("{reading:?}");

    let (town, degrees, rain) = reading;
    println!("{town} {degrees} {rain}");
}
Pune
31
2.5
("Pune", 31, 2.5)
Pune 31 2.5

The type of reading is (&str, i32, f64): the three types, in order, between parentheses. You can write it after a colon in the usual way.

A dot and a number read one part: reading.0 is the first part and reading.1 the second. Counting starts at 0. let (town, degrees, rain) = reading; takes the tuple apart and gives each part its own name in one step.

A tuple cannot be printed with plain {}. Use {:?}, as in {reading:?}.

The tuple with nothing in it, written (), is a type of its own. It is the value of a function that gives nothing back.

Arrays

An array is a fixed number of values that all have the same type. Write the values between square brackets.

fn main() {
    let marks = [72, 45, 90, 61, 38];

    println!("{}", marks[0]);
    println!("{}", marks[4]);
    println!("{}", marks.len());
    println!("{marks:?}");

    let mut counts = [0; 4];
    counts[2] = 7;
    println!("{counts:?}");
}
72
38
5
[72, 45, 90, 61, 38]
[0, 0, 7, 0]

Each value sits in its own slot, and every slot has a number, written under it here:

| 72 | 45 | 90 | 61 | 38 |
  0    1    2    3    4

That number is the index. It counts from 0, so marks[0] is the first value, marks[4] is the fifth, and the last index is always one less than the length. marks.len() is the length, as a usize.

[0; 4] is a short way to write four zeros. The value comes first, then a semicolon, then how many. Writing to one slot needs mut, the same as any other change.

The type of marks is [i32; 5]: the type of one value, a semicolon, and the length. The length is part of the type. An array can never grow or shrink, and a [i32; 5] and a [i32; 6] are different types.

An Index Past the End

Reading past the end of an array is an error. If the index is written in the program, the compiler catches it.

fn main() {
    let marks = [72, 45, 90];
    println!("{}", marks[3]);
}
error: this operation will panic at runtime
 --> src/main.rs:3:20
  |
3 |     println!("{}", marks[3]);
  |                    ^^^^^^^^ index out of bounds: the length is 3 but the index is 3

If the index is worked out while the program runs, the check happens then, and the program panics instead of reading memory that belongs to something else.

fn pick(marks: [i32; 3], position: usize) -> i32 {
    marks[position]
}

fn main() {
    let marks = [72, 45, 90];
    println!("{}", pick(marks, 2));
    println!("{}", pick(marks, 3));
}
90

thread 'main' (1303530) panicked at src/main.rs:2:5:
index out of bounds: the len is 3 but the index is 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

position has the type usize, because an index must be a usize. Declare it as an i32 and the program does not compile.

Every Index Is Checked

In C, reading past the end of an array reads whatever happens to be in memory there, and the program carries on with a wrong value. Rust checks every index, and stops the program the moment one is out of range.

The Size of Each Type

size_of::<T>() gives the number of bytes a type takes, with the type written in place of T. It is the quickest way to check what you have learnt about widths.

fn main() {
    println!("bool  {}", size_of::<bool>());
    println!("char  {}", size_of::<char>());
    println!("u8    {}", size_of::<u8>());
    println!("i32   {}", size_of::<i32>());
    println!("f64   {}", size_of::<f64>());
    println!("usize {}", size_of::<usize>());
    println!("(i32, i32) {}", size_of::<(i32, i32)>());
    println!("[i32; 4]   {}", size_of::<[i32; 4]>());
    println!("()    {}", size_of::<()>());
}
bool  1
char  4
u8    1
i32   4
f64   8
usize 8
(i32, i32) 8
[i32; 4]   16
()    0

A tuple takes the space of its parts added together, and an array takes the space of one value multiplied by the length. Every size in this table is known before the program runs.

Functions

A function is a named block of code. You write it once and call it by name as many times as you like. main is a function, and so is every other piece of code you write.

Declaring and Calling a Function

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

fn main() {
    greet();
    greet();
}
hello
hello

fn starts a function. Then comes the name, a pair of parentheses, and the body between braces. greet() calls it: the program jumps into the body, runs it, and comes back to the line after the call.

A function can be written above or below the function that calls it. The order in the file does not matter. Function names follow the same rule as variable names: small letters, with an underscore between words.

Parameters

A parameter is a value the function receives. Each one is a name and a type, written inside the parentheses. The type is not optional.

fn show_sum(a: i32, b: i32) {
    println!("{a} + {b} = {}", a + b);
}

fn main() {
    show_sum(3, 4);
    show_sum(10, 20);
}
3 + 4 = 7
10 + 20 = 30

The values in the call are called arguments. They are given to the parameters in order: 3 goes into a and 4 into b. Each argument must have the type the parameter asks for. show_sum(2.5, 4) does not compile, because 2.5 is not an i32.

Return Values

A function can give a value back to the caller. Write an arrow and the type of that value after the parentheses.

fn double(n: i32) -> i32 {
    n * 2
}

fn main() {
    println!("{}", double(21));
}
42

-> i32 says the function gives back an i32. The value it gives back is the last line of the body, n * 2, and that line has no semicolon. The call double(21) then stands for the value 42, and can be printed or stored like any other value.

The semicolon matters. Put one after n * 2 and the function no longer gives anything back.

fn double(n: i32) -> i32 {
    n * 2;
}

fn main() {
    println!("{}", double(21));
}
error[E0308]: mismatched types
 --> src/main.rs:1:22
  |
1 | fn double(n: i32) -> i32 {
  |    ------            ^^^ expected `i32`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
2 |     n * 2;
  |          - help: remove this semicolon to return this value

A line that ends in a semicolon is a statement: it does something and produces no value. A line with no semicolon at the end of a block is an expression: it produces a value, and that value leaves the block. The body of double now ends with a statement, so the function produces (), the empty tuple, and that is not an i32.

You can also give a value back with the word return. It leaves the function at once, from anywhere in the body, and it takes a semicolon.

fn area(width: f64, height: f64) -> f64 {
    return width * height;
}

Most Rust code uses the last line without a semicolon, and keeps return for leaving a function early, from the middle of the body.

A Function That Gives Nothing Back

A function with no arrow gives back (). You can catch that value, but there is nothing in it.

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

fn main() {
    let result = greet();
    println!("{result:?}");
}
hello
()

Read the Signature First

The first line of a function is its signature: the name, the parameters with their types, and the return type. It tells you everything you need to call the function, without reading the body. fn double(n: i32) -> i32 takes one whole number and gives one back.

Everything Together

This program uses all of the lesson. A constant, a function that converts a temperature, a function that gives back a tuple, and a function that takes an array and gives back its average.

const BOILING_POINT: f64 = 100.0;

fn to_fahrenheit(celsius: f64) -> f64 {
    celsius * 9.0 / 5.0 + 32.0
}

fn divide(a: u32, b: u32) -> (u32, u32) {
    (a / b, a % b)
}

fn average(marks: [u32; 4]) -> f64 {
    let mut total = 0;
    total += marks[0];
    total += marks[1];
    total += marks[2];
    total += marks[3];
    total as f64 / marks.len() as f64
}

fn main() {
    println!("{BOILING_POINT} C is {} F", to_fahrenheit(BOILING_POINT));
    println!("37.5 C is {:.1} F", to_fahrenheit(37.5));

    let (quotient, remainder) = divide(17, 5);
    println!("17 / 5 = {quotient} remainder {remainder}");

    let marks = [72, 45, 90, 61];
    println!("marks: {marks:?}");
    println!("average: {:.2}", average(marks));

    let first = marks[0] as u8;
    println!("first mark as bits: {first:08b}");
}
100 C is 212 F
37.5 C is 99.5 F
17 / 5 = 3 remainder 2
marks: [72, 45, 90, 61]
average: 67.00
first mark as bits: 01001000

Four parts of this program need extra explanation.

  • divide gives back a tuple: the whole-number result of the division and the remainder, together. The caller takes it apart with let (quotient, remainder) = divide(17, 5);.

  • let mut total = 0; has no type written. The next line adds a u32 to it, so the compiler makes total a u32.

  • total as f64 / marks.len() as f64 converts both sides to f64 before dividing, so the decimal part is kept. as is applied before /, so no parentheses are needed.

  • marks[0] as u8 narrows the first mark to 8 bits so that {first:08b} prints exactly eight of them.

Reference

Written asWhat it does
let x = 5;Declare a variable. The type is worked out from the value.
let x: u8 = 5;Declare a variable with a type.
let mut x = 5;Declare a variable that can change.
x += 1;Add to a variable and store the result. Also -= *= /= %=.
let x = x + 1;Shadow: a new variable with the same name.
const MAX: u32 = 100;A constant. The type is required.
i8 i16 i32 i64 i128Signed integers. i32 is the default.
u8 u16 u32 u64 u128Unsigned integers.
usizeThe type for a length or an index.
f32 f64Floating point numbers. f64 is the default.
booltrue or false.
charOne character, in single quotes.
&strA piece of text, in double quotes.
x as u8Convert x to a u8. Keeps the bits that fit.
(1, 2.5)A tuple. Read the parts with .0 and .1.
let (a, b) = pair;Take a tuple apart.
{[1, 2, 3]}An array. Its type is [i32; 3].
{[0; 8]}An array of eight zeros.
a[0]The first value in the array.
a.len()The length of the array, as a usize.
size_of::<T>()The number of bytes a type takes.
fn f(a: i32) -> i32A function taking an i32 and giving one back.
return x;Leave the function now with the value x.
{x:?}Print a tuple or an array.
{x:.2}Print a number with two decimal places.
{x:08b}Print the bits of a number, eight wide.

Check what stuck

The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.

Start practice →