Contents

Ch.3 — Common Programming Concepts

Chapter 3

Common Programming Concepts


This chapter covers concepts that appear in almost every programming language and how they work in Rust. Many programming languages have much in common at their core. None of these concepts is unique to Rust, but the chapter discusses them in the context of Rust and explains the conventions around using them.

Specifically, you’ll learn about variables, basic types, functions, comments, and control flow. These foundations will be in every Rust program, and learning them early gives you a strong core to start from.

  • 3.1 Variables and Mutability
  • 3.2 Data Types
  • 3.3 Functions
  • 3.4 Comments
  • 3.5 Control Flow

The Rust Programming Language · Ch.3 Common Programming Concepts

1

Chapter 3 · Introduction

Keywords

Like other languages, Rust has a set of words that belong to the language itself.

Definition 3.1 (Keyword). A word reserved for use by the Rust language only. You cannot use keywords as names of variables or functions.

  • Most keywords have special meanings, and you’ll use them to do various tasks in your Rust programs (for example let, fn, if, loop).
  • A few have no current functionality but have been reserved for functionality that might be added to Rust in the future.
  • The full list of keywords is in Appendix A.

The Rust Programming Language · Ch.3 Common Programming Concepts

2

Chapter 3 · 3.1 Variables and Mutability

Variables are immutable by default

As seen in Chapter 2 (“Storing Values with Variables”), variables are immutable by default. This is one of many nudges Rust gives you to write code that takes advantage of the safety and easy concurrency Rust offers. You still have the option to make variables mutable; this section explores how and why Rust encourages you to favor immutability, and why sometimes you might want to opt out.

Definition 3.2 (Immutable variable). A variable whose value, once bound to its name, cannot be changed.

To illustrate, run cargo new variables in your projects directory, then replace the code in src/main.rs with this code, which won’t compile just yet:

fn main() {

    let x = 5;

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

    x = 6;

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

}

Save and run the program using cargo run. You should receive an immutability error, shown on the next slide.

The Rust Programming Language · Ch.3 Common Programming Concepts

3

Chapter 3 · 3.1 Variables and Mutability

The immutability error

$ cargo run

   Compiling variables v0.1.0 (file:///projects/variables)

error[E0384]: cannot assign twice to immutable variable `x`

 --> src/main.rs:4:5

  |

2 |     let x = 5;

  |         - first assignment to `x`

3 |     println!("The value of x is: {x}");

4 |     x = 6;

  |     ^^^^^ cannot assign twice to immutable variable

  |

help: consider making this binding mutable

  |

2 |     let mut x = 5;

  |         +++

 

For more information about this error, try `rustc --explain E0384`.

error: could not compile `variables` (bin "variables") due to 1 previous error

The Rust Programming Language · Ch.3 Common Programming Concepts

4

Chapter 3 · 3.1 Variables and Mutability

Why immutability errors are caught at compile time

This example shows how the compiler helps you find errors in your programs. Compiler errors can be frustrating, but really they only mean your program isn’t safely doing what you want it to do yet; they do not mean that you’re not a good programmer! Experienced Rustaceans still get compiler errors.

You received the error message cannot assign twice to immutable variable `x` because you tried to assign a second value to the immutable x variable.

It’s important to get compile-time errors when we attempt to change a value that’s designated as immutable, because this very situation can lead to bugs. If one part of our code operates on the assumption that a value will never change and another part changes that value, the first part may not do what it was designed to do. The cause of this kind of bug can be difficult to track down after the fact, especially when the second piece of code changes the value only sometimes.

The Rust compiler guarantees that when you state that a value won’t change, it really won’t change, so you don’t have to keep track of it yourself. Your code is thus easier to reason through.

The Rust Programming Language · Ch.3 Common Programming Concepts

5

Chapter 3 · 3.1 Variables and Mutability

Opting in to mutability with mut

But mutability can be very useful and can make code more convenient to write. Although variables are immutable by default, you can make them mutable by adding mut in front of the variable name, as you did in Chapter 2. Adding mut also conveys intent to future readers of the code: it indicates that other parts of the code will be changing this variable’s value.

Definition 3.3 (Mutable variable). A variable declared with let mut, whose bound value may be changed later.

For example, change src/main.rs to the following:

fn main() {

    let mut x = 5;

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

    x = 6;

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

}

The Rust Programming Language · Ch.3 Common Programming Concepts

6

Chapter 3 · 3.1 Variables and Mutability

Running the mutable version

When we run the program now, we get this:

$ cargo run

   Compiling variables v0.1.0 (file:///projects/variables)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s

     Running `target/debug/variables`

The value of x is: 5

The value of x is: 6

We’re allowed to change the value bound to x from 5 to 6 when mut is used.

Remark. Ultimately, deciding whether to use mutability or not is up to you and depends on what you think is clearest in that particular situation.

The Rust Programming Language · Ch.3 Common Programming Concepts

7

Chapter 3 · 3.1 Variables and Mutability

Declaring constants

Definition 3.4 (Constant). Like an immutable variable, a value that is bound to a name and is not allowed to change — but with a few differences from variables.

  • You aren’t allowed to use mut with constants: they aren’t just immutable by default, they’re always immutable.
  • You declare constants with the const keyword instead of let, and the type of the value must be annotated (types and annotations come in “Data Types”; just know you must always annotate the type).
  • Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of code need to know about.
  • Constants may be set only to a constant expression, not to the result of a value that could only be computed at runtime.

Here’s an example of a constant declaration:

const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

The Rust Programming Language · Ch.3 Common Programming Concepts

8

Chapter 3 · 3.1 Variables and Mutability

Naming and using constants

  • The constant’s name is THREE_HOURS_IN_SECONDS. Its value is 60 (seconds in a minute) times 60 (minutes in an hour) times 3 (the number of hours we want to count in this program).
  • Rust’s naming convention for constants is all uppercase with underscores between words.
  • The compiler can evaluate a limited set of operations at compile time. That lets us write the value in a way that’s easier to understand and verify, rather than setting the constant to 10,800. The Rust Reference’s section on constant evaluation lists which operations are allowed.
  • Constants are valid for the entire time a program runs, within the scope in which they were declared. This makes them useful for values in your application domain that multiple parts of the program might need to know about, such as the maximum number of points any player of a game may earn, or the speed of light.
  • Naming hardcoded values used throughout your program as constants conveys the meaning of that value to future maintainers, and leaves only one place to change if the hardcoded value needs updating.

The Rust Programming Language · Ch.3 Common Programming Concepts

9

Chapter 3 · 3.1 Variables and Mutability

Shadowing

As you saw in the guessing game tutorial in Chapter 2, you can declare a new variable with the same name as a previous variable.

Definition 3.5 (Shadowing). Declaring a new variable with the same name as a previous one. Rustaceans say the first variable is shadowed by the second: the second variable is what the compiler sees when you use the name.

In effect, the second variable overshadows the first, taking any uses of the variable name to itself until either it itself is shadowed or the scope ends.

We shadow a variable by using the same variable’s name and repeating the let keyword, as the program on the next slide does.

The Rust Programming Language · Ch.3 Common Programming Concepts

10

Chapter 3 · 3.1 Variables and Mutability

Shadowing in an inner scope

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}");

}

The program first binds x to 5. Then it creates a new variable x by repeating let x =, taking the original value and adding 1, so x is 6. Within an inner scope created with curly brackets, the third let also shadows x, creating a new variable that multiplies the previous value by 2: x is 12. When that scope is over, the inner shadowing ends and x returns to being 6.

The Rust Programming Language · Ch.3 Common Programming Concepts

11

Chapter 3 · 3.1 Variables and Mutability

Shadowing versus mut

When we run the shadowing program, it outputs the following:

$ cargo run

   Compiling variables v0.1.0 (file:///projects/variables)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s

     Running `target/debug/variables`

The value of x in the inner scope is: 12

The value of x is: 6

Shadowing is different from marking a variable as mut: we’ll get a compile-time error if we accidentally try to reassign to this variable without using the let keyword. By using let, we can perform a few transformations on a value but have the variable be immutable after those transformations have completed.

The Rust Programming Language · Ch.3 Common Programming Concepts

12

Chapter 3 · 3.1 Variables and Mutability

Shadowing can change the type

The other difference between mut and shadowing: because we’re effectively creating a new variable when we use let again, we can change the type of the value but reuse the same name. Say our program asks a user how many spaces they want between some text by inputting space characters, and then we want to store that input as a number:

Shadowing — compiles:

fn main() {

    let spaces = "   ";

    let spaces = spaces.len();

}

The first spaces is a string type, the second a number type. Shadowing spares us from coming up with different names, such as spaces_str and spaces_num; we can reuse the simpler spaces name.

mut — if we try this instead, we get a compile-time error:

fn main() {

    let mut spaces = "   ";

    spaces = spaces.len();

}

The Rust Programming Language · Ch.3 Common Programming Concepts

13

Chapter 3 · 3.1 Variables and Mutability

mut cannot change a variable’s type

The error says we’re not allowed to mutate a variable’s type:

$ cargo run

   Compiling variables v0.1.0 (file:///projects/variables)

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`

 

For more information about this error, try `rustc --explain E0308`.

error: could not compile `variables` (bin "variables") due to 1 previous error

Now that we’ve explored how variables work, let’s look at more data types they can have.

The Rust Programming Language · Ch.3 Common Programming Concepts

14

Chapter 3 · 3.2 Data Types

Every value has a data type

Definition 3.6 (Data type). What every value in Rust has: it tells Rust what kind of data is being specified, so that it knows how to work with that data. This section looks at two subsets: scalar and compound types.

Definition 3.7 (Statically typed). A language that must know the types of all variables at compile time. Rust is statically typed.

The compiler can usually infer the type we want from the value and how we use it. When many types are possible — such as converting a String to a numeric type with parse in Chapter 2’s “Comparing the Guess to the Secret Number” — we must add a type annotation, like this:

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

You’ll see different type annotations for other data types.

The Rust Programming Language · Ch.3 Common Programming Concepts

15

Chapter 3 · 3.2 Data Types

When the compiler needs a type annotation

Without the : u32 annotation, the compiler needs more information about the type we want:

$ cargo build

   Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)

error[E0284]: type annotations needed

 --> src/main.rs:2:9

  |

2 |     let guess = "42".parse().expect("Not a number!");

  |         ^^^^^        ----- type must be known at this point

  |

  = note: cannot satisfy `<_ as FromStr>::Err == _`

help: consider giving `guess` an explicit type

  |

2 |     let guess: /* Type */ = "42".parse().expect("Not a number!");

  |              ++++++++++++

 

For more information about this error, try `rustc --explain E0284`.

error: could not compile `no_type_annotations` (bin "no_type_annotations") due to 1 previous error

The Rust Programming Language · Ch.3 Common Programming Concepts

16

Chapter 3 · 3.2 Data Types

Scalar types: integers

Definition 3.8 (Scalar type). A type that represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters.

Definition 3.9 (Integer). A number without a fractional component.

Chapter 2 used the integer type u32: an unsigned integer (signed integer types start with i instead of u) that takes up 32 bits of space. Table 3.1 shows Rust’s built-in integer types; any of these variants can declare the type of an integer value.

Table 3.1: Integer types in Rust

LengthSignedUnsigned
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
Architecture-dependentisizeusize

The Rust Programming Language · Ch.3 Common Programming Concepts

17

Chapter 3 · 3.2 Data Types

Signed and unsigned ranges

Each variant can be either signed or unsigned and has an explicit size.

Definition 3.10 (Signed and unsigned). Whether it’s possible for the number to be negative: whether the number needs a sign with it (signed), or will only ever be positive and can therefore be represented without a sign (unsigned).

It’s like writing numbers on paper: when the sign matters, a number is shown with a plus or minus sign; when it’s safe to assume the number is positive, it’s shown with no sign. Signed numbers are stored using two’s complement representation.

  • Each signed variant stores numbers from −(2ⁿ⁻¹) to 2ⁿ⁻¹ − 1 inclusive, where n is the number of bits the variant uses. So an i8 stores −(2⁷) to 2⁷ − 1, which equals −128 to 127.
  • Unsigned variants store numbers from 0 to 2ⁿ − 1, so a u8 stores 0 to 2⁸ − 1, which equals 0 to 255.
  • isize and usize depend on the architecture of the computer your program runs on: 64 bits on a 64-bit architecture and 32 bits on a 32-bit architecture.

The Rust Programming Language · Ch.3 Common Programming Concepts

18

Chapter 3 · 3.2 Data Types

Integer literals and defaults

You can write integer literals in any of the forms in Table 3.2. Number literals that can be multiple numeric types allow a type suffix, such as 57u8, to designate the type. Number literals can also use _ as a visual separator to make the number easier to read: 1_000 has the same value as 1000.

Which integer type should you use? If you’re unsure, Rust’s defaults are generally good places to start: integer types default to i32. The primary situation in which you’d use isize or usize is when indexing some sort of collection.

Table 3.2: Integer literals in Rust

Number literalsExample
Decimal98_222
Hex0xff
Octal0o77
Binary0b1111_0000
Byte (u8 only)b'A'

The Rust Programming Language · Ch.3 Common Programming Concepts

19

Chapter 3 · 3.2 Data Types

Integer overflow in debug builds

Say you have a variable of type u8, which can hold values between 0 and 255. If you try to change the variable to a value outside that range, such as 256, integer overflow occurs.

Definition 3.11 (Integer overflow). Assigning an integer variable a value outside the range its type can hold. It results in one of two behaviors, depending on whether you compile in debug or release mode.

When you’re compiling in debug mode, Rust includes checks for integer overflow that cause your program to panic at runtime if this behavior occurs.

Definition 3.12 (Panic). Rust’s term for a program exiting with an error (panicking). Panics are discussed in more depth in “Unrecoverable Errors with panic!” in Chapter 9.

The Rust Programming Language · Ch.3 Common Programming Concepts

20

Chapter 3 · 3.2 Data Types

Overflow in release builds, and handling it explicitly

When you’re compiling in release mode with the --release flag, Rust does not include checks for integer overflow that cause panics. Instead, if overflow occurs, Rust performs two’s complement wrapping.

Definition 3.13 (Two’s complement wrapping). Values greater than the maximum value the type can hold “wrap around” to the minimum of the values the type can hold. For a u8, 256 becomes 0, 257 becomes 1, and so on.

The program won’t panic, but the variable will have a value that probably isn’t what you were expecting. Relying on integer overflow’s wrapping behavior is considered an error. To explicitly handle the possibility of overflow, use these families of methods the standard library provides for primitive numeric types:

  • Wrap in all compilation modes with the wrapping_* methods, such as wrapping_add.
  • Return the None value if there is overflow with the checked_* methods.
  • Return the value and a Boolean indicating whether there was overflow with the overflowing_* methods.
  • Saturate at the value’s minimum or maximum values with the saturating_* methods.

The Rust Programming Language · Ch.3 Common Programming Concepts

21

Chapter 3 · 3.2 Data Types

Floating-point types

Definition 3.14 (Floating-point number). A number with a decimal point. Rust has two primitive floating-point types, f32 and f64, which are 32 bits and 64 bits in size.

  • The default type is f64, because on modern CPUs it’s roughly the same speed as f32 but is capable of more precision.
  • All floating-point types are signed.
  • Floating-point numbers are represented according to the IEEE-754 standard.

Here’s an example that shows floating-point numbers in action:

src/main.rs

fn main() {

    let x = 2.0; // f64

 

    let y: f32 = 3.0; // f32

}

The Rust Programming Language · Ch.3 Common Programming Concepts

22

Chapter 3 · 3.2 Data Types

Numeric operations

Rust supports the basic mathematical operations you’d expect for all the number types: addition, subtraction, multiplication, division, and remainder.

Integer division truncates toward zero to the nearest integer (-5 / 3 gives -1).

Each expression in these let statements uses a mathematical operator and evaluates to a single value, which is then bound to a variable.

Appendix B lists all the operators Rust provides.

fn main() {

    // addition

    let sum = 5 + 10;

 

    // subtraction

    let difference = 95.5 - 4.3;

 

    // multiplication

    let product = 4 * 30;

 

    // division

    let quotient = 56.7 / 32.2;

    let truncated = -5 / 3; // Results in -1

 

    // remainder

    let remainder = 43 % 5;

}

The Rust Programming Language · Ch.3 Common Programming Concepts

23

Chapter 3 · 3.2 Data Types

The Boolean type

Definition 3.15 (Boolean). A type with two possible values, true and false, as in most other programming languages. In Rust it is specified with bool, and Booleans are one byte in size.

For example:

src/main.rs

fn main() {

    let t = true;

 

    let f: bool = false; // with explicit type annotation

}

The main way to use Boolean values is through conditionals, such as an if expression. How if expressions work in Rust is covered in section 3.5, “Control Flow”.

The Rust Programming Language · Ch.3 Common Programming Concepts

24

Chapter 3 · 3.2 Data Types

The character type

Rust’s char type is the language’s most primitive alphabetic type. Some examples of declaring char values:

fn main() {

    let c = 'z';

    let z: char = 'ℤ'; // with explicit type annotation

    let heart_eyed_cat = '😻';

}

  • char literals use single quotation marks, as opposed to string literals, which use double quotation marks.
  • char is 4 bytes in size and represents a Unicode scalar value, so it can represent much more than ASCII: accented letters; Chinese, Japanese, and Korean characters; emojis; and zero-width spaces are all valid char values.
  • Unicode scalar values range from U+0000 to U+D7FF and U+E000 to U+10FFFF inclusive.
  • A “character” isn’t really a concept in Unicode, so your intuition for what a “character” is may not match what a char is in Rust. Chapter 8, “Storing UTF-8 Encoded Text with Strings”, discusses this in detail.

The Rust Programming Language · Ch.3 Common Programming Concepts

25

Chapter 3 · 3.2 Data Types

Compound types: the tuple

Definition 3.16 (Compound type). A type that groups multiple values into one type. Rust has two primitive compound types: tuples and arrays.

Definition 3.17 (Tuple). A general way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length: once declared, they cannot grow or shrink in size.

We create a tuple by writing a comma-separated list of values inside parentheses. Each position in the tuple has a type, and the types of the different values don’t have to be the same. This example adds optional type annotations:

src/main.rs

fn main() {

    let tup: (i32, f64, u8) = (500, 6.4, 1);

}

The Rust Programming Language · Ch.3 Common Programming Concepts

26

Chapter 3 · 3.2 Data Types

Destructuring a tuple

The variable tup binds to the entire tuple, because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this:

src/main.rs

fn main() {

    let tup = (500, 6.4, 1);

 

    let (x, y, z) = tup;

 

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

}

This program first creates a tuple and binds it to the variable tup. It then uses a pattern with let to take tup and turn it into three separate variables, x, y, and z. This is called destructuring, because it breaks the single tuple into three parts. Finally, the program prints the value of y, which is 6.4.

The Rust Programming Language · Ch.3 Common Programming Concepts

27

Chapter 3 · 3.2 Data Types

Accessing tuple elements; the unit type

We can also access a tuple element directly with a period (.) followed by the index of the value we want. For example:

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;

}

This program creates the tuple x and then accesses each element using its index. As with most programming languages, the first index in a tuple is 0.

Definition 3.18 (Unit). The tuple without any values. This value and its type are both written () and represent an empty value or an empty return type. Expressions implicitly return the unit value if they don’t return any other value.

The Rust Programming Language · Ch.3 Common Programming Concepts

28

Chapter 3 · 3.2 Data Types

The array type

Definition 3.19 (Array). A collection of multiple values in which, unlike a tuple, every element must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length.

We write the values in an array as a comma-separated list inside square brackets:

fn main() {

    let a = [1, 2, 3, 4, 5];

}

Arrays are useful when you want your data allocated on the stack, the same as the other types seen so far, rather than the heap (Chapter 4 discusses the stack and the heap), or when you want to ensure that you always have a fixed number of elements.

Remark. An array isn’t as flexible as the vector type. A vector is a similar collection type provided by the standard library that is allowed to grow or shrink in size, because its contents live on the heap. If you’re unsure whether to use an array or a vector, chances are you should use a vector. Chapter 8 discusses vectors in more detail.

The Rust Programming Language · Ch.3 Common Programming Concepts

29

Chapter 3 · 3.2 Data Types

Arrays for a fixed number of elements; array types

Arrays are more useful when you know the number of elements will not need to change. If you were using the names of the months in a program, you would probably use an array rather than a vector, because you know it will always contain 12 elements:

let months = ["January", "February", "March", "April", "May", "June", "July",

              "August", "September", "October", "November", "December"];

You write an array’s type using square brackets with the type of each element, a semicolon, and then the number of elements in the array, like so:

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

Here, i32 is the type of each element. After the semicolon, the number 5 indicates the array contains five elements.

The Rust Programming Language · Ch.3 Common Programming Concepts

30

Chapter 3 · 3.2 Data Types

Initializing every element to one value

You can also initialize an array to contain the same value for each element by specifying the initial value, followed by a semicolon, and then the length of the array, in square brackets:

let a = [3; 5];

The array named a will contain 5 elements that are all initially set to the value 3. This is the same as writing let a = [3, 3, 3, 3, 3]; but in a more concise way.

Array element access

An array is a single chunk of memory of a known, fixed size that can be allocated on the stack. You can access elements of an array using indexing, as the next slide shows.

The Rust Programming Language · Ch.3 Common Programming Concepts

31

Chapter 3 · 3.2 Data Types

Accessing array elements

src/main.rs

fn main() {

    let a = [1, 2, 3, 4, 5];

 

    let first = a[0];

    let second = a[1];

}

The variable named first will get the value 1, because that is the value at index [0] in the array. The variable named second will get the value 2 from index [1] in the array.

The Rust Programming Language · Ch.3 Common Programming Concepts

32

Chapter 3 · 3.2 Data Types

Invalid array element access

What happens if you try to access an element past the end of the array? Say you run this code, similar to the guessing game in Chapter 2, to get an array index from the user:

src/main.rs

use std::io;

 

fn main() {

    let a = [1, 2, 3, 4, 5];

 

    println!("Please enter an array index.");

 

    let mut index = String::new();

 

    io::stdin()

        .read_line(&mut index)

        .expect("Failed to read line");

 

The Rust Programming Language · Ch.3 Common Programming Concepts

33

Chapter 3 · 3.2 Data Types

Invalid array element access (continued)

    let index: usize = index

        .trim()

        .parse()

        .expect("Index entered was not a number");

 

    let element = a[index];

 

    println!("The value of the element at index {index} is: {element}");

}

This code compiles successfully. Run with cargo run and enter 0, 1, 2, 3, or 4, and it prints the value at that index. Enter a number past the end of the array, such as 10, and you’ll see output like this:

thread 'main' panicked at src/main.rs:19:19:

index out of bounds: the len is 5 but the index is 10

note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

The Rust Programming Language · Ch.3 Common Programming Concepts

34

Chapter 3 · 3.2 Data Types

Why Rust panics on an invalid index

The program resulted in a runtime error at the point of using an invalid value in the indexing operation. It exited with an error message and didn’t execute the final println! statement.

When you attempt to access an element using indexing, Rust checks that the index you’ve specified is less than the array length. If the index is greater than or equal to the length, Rust will panic. This check has to happen at runtime, especially in this case, because the compiler can’t possibly know what value a user will enter when they run the code later.

This is an example of Rust’s memory safety principles in action. In many low-level languages, this kind of check is not done, and when you provide an incorrect index, invalid memory can be accessed. Rust protects you against this kind of error by immediately exiting instead of allowing the memory access and continuing.

Remark. Chapter 9 discusses more of Rust’s error handling, and how you can write readable, safe code that neither panics nor allows invalid memory access.

The Rust Programming Language · Ch.3 Common Programming Concepts

35

Chapter 3 · 3.3 Functions

Defining functions

Functions are prevalent in Rust code. You’ve already seen one of the most important: main, the entry point of many programs. You’ve also seen the fn keyword, which declares new functions.

Definition 3.20 (Snake case). The conventional style for Rust function and variable names: all letters lowercase, with underscores separating words.

We define a function by entering fn followed by a function name and a set of parentheses. The curly brackets tell the compiler where the function body begins and ends.

A program with an example function definition — src/main.rs

fn main() {

    println!("Hello, world!");

 

    another_function();

}

 

fn another_function() {

    println!("Another function.");

}

The Rust Programming Language · Ch.3 Common Programming Concepts

36

Chapter 3 · 3.3 Functions

Calling functions

We call any function we’ve defined by entering its name followed by a set of parentheses. Because another_function is defined in the program, it can be called from inside main. Note that it is defined after main; it could have been defined before as well. Rust doesn’t care where you define your functions, only that they’re defined somewhere in a scope that can be seen by the caller.

Start a new binary project named functions, place the example in src/main.rs, and run it:

$ cargo run

   Compiling functions v0.1.0 (file:///projects/functions)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s

     Running `target/debug/functions`

Hello, world!

Another function.

The lines execute in the order in which they appear in main: first the “Hello, world!” message prints, and then another_function is called and its message is printed.

The Rust Programming Language · Ch.3 Common Programming Concepts

37

Chapter 3 · 3.3 Functions

Parameters

Definition 3.21 (Parameter). A special variable that is part of a function’s signature. When a function has parameters, you can provide it with concrete values for them.

Definition 3.22 (Argument). Technically, a concrete value passed in for a parameter when you call a function. In casual conversation, people use parameter and argument interchangeably, for either the variables in a function’s definition or the concrete values passed in.

In this version of another_function we add a parameter:

fn main() {

    another_function(5);

}

 

fn another_function(x: i32) {

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

}

The Rust Programming Language · Ch.3 Common Programming Concepts

38

Chapter 3 · 3.3 Functions

Parameters must declare their types

Try running this program; you should get the following output:

$ cargo run

   Compiling functions v0.1.0 (file:///projects/functions)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.21s

     Running `target/debug/functions`

The value of x is: 5

The declaration of another_function has one parameter named x, whose type is specified as i32. When we pass 5 in to another_function, the println! macro puts 5 where the pair of curly brackets containing x was in the format string.

In function signatures, you must declare the type of each parameter. This is a deliberate decision in Rust’s design: requiring type annotations in function definitions means the compiler almost never needs you to use them elsewhere in the code to figure out what type you mean. The compiler can also give more helpful error messages if it knows what types the function expects.

The Rust Programming Language · Ch.3 Common Programming Concepts

39

Chapter 3 · 3.3 Functions

Multiple parameters

When defining multiple parameters, separate the parameter declarations with commas, like this:

src/main.rs

fn main() {

    print_labeled_measurement(5, 'h');

}

 

fn print_labeled_measurement(value: i32, unit_label: char) {

    println!("The measurement is: {value}{unit_label}");

}

This example creates a function named print_labeled_measurement with two parameters. The first parameter is named value and is an i32. The second is named unit_label and is type char. The function then prints text containing both the value and the unit_label.

The Rust Programming Language · Ch.3 Common Programming Concepts

40

Chapter 3 · 3.3 Functions

Running print_labeled_measurement

Replace the program in your functions project’s src/main.rs file with the preceding example and run it using cargo run:

$ cargo run

   Compiling functions v0.1.0 (file:///projects/functions)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s

     Running `target/debug/functions`

The measurement is: 5h

Because we called the function with 5 as the value for value and 'h' as the value for unit_label, the program output contains those values.

The Rust Programming Language · Ch.3 Common Programming Concepts

41

Chapter 3 · 3.3 Functions

Statements and expressions

Function bodies are made up of a series of statements optionally ending in an expression. So far, the functions covered haven’t included an ending expression, but you have seen an expression as part of a statement. Because Rust is an expression-based language, this is an important distinction to understand. Other languages don’t have the same distinctions, so let’s look at what statements and expressions are and how their differences affect the bodies of functions.

Definition 3.23 (Statement). An instruction that performs some action and does not return a value.

Definition 3.24 (Expression). Code that evaluates to a resultant value.

We’ve actually already used statements and expressions. Creating a variable and assigning a value to it with the let keyword is a statement: in Listing 3.1, let y = 6; is a statement.

The Rust Programming Language · Ch.3 Common Programming Concepts

42

Chapter 3 · 3.3 Functions

Statements do not return values

Listing 3.1: A main function declaration containing one statement — src/main.rs

fn main() {

    let y = 6;

}

Function definitions are also statements; the entire preceding example is a statement in itself. (As we’ll see shortly, calling a function is not a statement, though.)

Statements do not return values. Therefore, you can’t assign a let statement to another variable, as the following code tries to do; you’ll get an error:

src/main.rs

fn main() {

    let x = (let y = 6);

}

The Rust Programming Language · Ch.3 Common Programming Concepts

43

Chapter 3 · 3.3 Functions

Error: a let statement is not an expression

When you run this program, the error you’ll get looks like this:

$ cargo run

   Compiling functions v0.1.0 (file:///projects/functions)

error: expected expression, found `let` statement

 --> src/main.rs:2:14

  |

2 |     let x = (let y = 6);

  |              ^^^

  |

  = note: only supported directly in conditions of `if` and `while` expressions

 

The output continues on the next slide with a warning about the parentheses.

The Rust Programming Language · Ch.3 Common Programming Concepts

44

Chapter 3 · 3.3 Functions

Error: a let statement is not an expression (continued)

Output (continued)

warning: unnecessary parentheses around assigned value

 --> src/main.rs:2:13

  |

2 |     let x = (let y = 6);

  |             ^         ^

  |

  = note: `#[warn(unused_parens)]` (part of `#[warn(unused)]`) on by default

help: remove these parentheses

  |

2 -     let x = (let y = 6);

2 +     let x = let y = 6 ;

  |

 

warning: `functions` (bin "functions") generated 1 warning

error: could not compile `functions` (bin "functions") due to 1 previous error; 1 warning emitted

The Rust Programming Language · Ch.3 Common Programming Concepts

45

Chapter 3 · 3.3 Functions

Expressions evaluate to values

The let y = 6 statement does not return a value, so there isn’t anything for x to bind to. This is different from other languages, such as C and Ruby, where the assignment returns the value of the assignment: there you can write x = y = 6 and have both x and y have the value 6. That is not the case in Rust.

Expressions evaluate to a value and make up most of the rest of the code you’ll write in Rust. A math operation such as 5 + 6 is an expression that evaluates to 11. Expressions can be part of statements: in Listing 3.1, the 6 in let y = 6; is an expression that evaluates to 6. Calling a function is an expression. Calling a macro is an expression. A new scope block created with curly brackets is an expression, as the next slide shows.

The Rust Programming Language · Ch.3 Common Programming Concepts

46

Chapter 3 · 3.3 Functions

Blocks are expressions

src/main.rs

fn main() {

    let y = {

        let x = 3;

        x + 1

    };

 

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

}

This expression:

{

    let x = 3;

    x + 1

}

is a block that, in this case, evaluates to 4. That value gets bound to y as part of the let statement.

Note the x + 1 line without a semicolon at the end, unlike most lines you’ve seen so far. Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, and it will then not return a value. Keep this in mind as you explore function return values and expressions next.

The Rust Programming Language · Ch.3 Common Programming Concepts

47

Chapter 3 · 3.3 Functions

Functions with return values

Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow (->). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function. You can return early from a function by using the return keyword and specifying a value, but most functions return the last expression implicitly. Here’s an example of a function that returns a value:

src/main.rs

fn five() -> i32 {

    5

}

 

fn main() {

    let x = five();

 

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

}

The Rust Programming Language · Ch.3 Common Programming Concepts

48

Chapter 3 · 3.3 Functions

Using a function’s return value

There are no function calls, macros, or even let statements in the five function — just the number 5 by itself. That’s a perfectly valid function in Rust. Note that the function’s return type is specified too, as -> i32. Try running this code; the output should look like this:

$ cargo run

   Compiling functions v0.1.0 (file:///projects/functions)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s

     Running `target/debug/functions`

The value of x is: 5

The 5 in five is the function’s return value, which is why the return type is i32. There are two important bits. First, the line let x = five(); shows that we’re using the return value of a function to initialize a variable. Because five returns a 5, that line is the same as:

let x = 5;

The Rust Programming Language · Ch.3 Common Programming Concepts

49

Chapter 3 · 3.3 Functions

Returning the final expression

Second, the five function has no parameters and defines the type of the return value, but the body of the function is a lonely 5 with no semicolon, because it’s an expression whose value we want to return.

Let’s look at another example:

fn main() {

    let x = plus_one(5);

 

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

}

 

fn plus_one(x: i32) -> i32 {

    x + 1

}

Running this code will print The value of x is: 6. But what happens if we place a semicolon at the end of the line containing x + 1, changing it from an expression to a statement?

The Rust Programming Language · Ch.3 Common Programming Concepts

50

Chapter 3 · 3.3 Functions

Adding a semicolon to the final expression

src/main.rs

fn main() {

    let x = plus_one(5);

 

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

}

 

fn plus_one(x: i32) -> i32 {

    x + 1;

}

The only change is the semicolon after x + 1. Compiling this code produces an error, shown on the next slide.

The Rust Programming Language · Ch.3 Common Programming Concepts

51

Chapter 3 · 3.3 Functions

The mismatched types error

$ cargo run

   Compiling functions v0.1.0 (file:///projects/functions)

error[E0308]: mismatched types

 --> src/main.rs:7:24

  |

7 | fn plus_one(x: i32) -> i32 {

  |    --------            ^^^ expected `i32`, found `()`

  |    |

  |    implicitly returns `()` as its body has no tail or `return` expression

8 |     x + 1;

  |          - help: remove this semicolon to return this value

 

For more information about this error, try `rustc --explain E0308`.

error: could not compile `functions` (bin "functions") due to 1 previous error

mismatched types reveals the core issue: plus_one says it returns an i32, but statements don’t evaluate to a value, which is expressed by (), the unit type. Nothing is returned, contradicting the definition. Rust suggests removing the semicolon, which would fix the error.

The Rust Programming Language · Ch.3 Common Programming Concepts

52

Chapter 3 · 3.4 Comments

Comments

All programmers strive to make their code easy to understand, but sometimes extra explanation is warranted.

Definition 3.25 (Comment). Text that programmers leave in their source code, which the compiler ignores but that people reading the source code may find useful.

Here’s a simple comment:

// hello, world

In Rust, the idiomatic comment style starts a comment with two slashes, and the comment continues until the end of the line. For comments that extend beyond a single line, you’ll need to include // on each line, like this:

// So we're doing something complicated here, long enough that we need

// multiple lines of comments to do it! Whew! Hopefully, this comment will

// explain what's going on.

The Rust Programming Language · Ch.3 Common Programming Concepts

53

Chapter 3 · 3.4 Comments

Where comments go

Comments can also be placed at the end of lines containing code:

fn main() {

    let lucky_number = 7; // I'm feeling lucky today

}

But you’ll more often see them used in this format, with the comment on a separate line above the code it’s annotating:

fn main() {

    // I'm feeling lucky today

    let lucky_number = 7;

}

Remark. Rust also has another kind of comment, documentation comments, discussed in “Publishing a Crate to Crates.io” in Chapter 14.

The Rust Programming Language · Ch.3 Common Programming Concepts

54

Chapter 3 · 3.5 Control Flow

if expressions

Running some code depending on whether a condition is true, and running some code repeatedly while a condition is true, are basic building blocks in most programming languages. The most common constructs in Rust that let you control the flow of execution are if expressions and loops.

An if expression lets you branch your code depending on conditions: “If this condition is met, run this block of code. If the condition is not met, do not run this block of code.”

Create a new project called branches in your projects directory, and in src/main.rs input the code on the right.

src/main.rs

fn main() {

    let number = 3;

 

    if number < 5 {

        println!("condition was true");

    } else {

        println!("condition was false");

    }

}

The Rust Programming Language · Ch.3 Common Programming Concepts

55

Chapter 3 · 3.5 Control Flow

How an if expression is built

All if expressions start with the keyword if, followed by a condition. Here, the condition checks whether or not the variable number has a value less than 5. The block of code to execute if the condition is true is placed immediately after the condition, inside curly brackets.

Definition 3.26 (Arm). A block of code associated with a condition in an if expression — just like the arms in match expressions discussed in Chapter 2’s “Comparing the Guess to the Secret Number”.

Optionally, we can also include an else expression, as we chose to do here, to give the program an alternative block of code to execute should the condition evaluate to false. If you don’t provide an else expression and the condition is false, the program will just skip the if block and move on to the next bit of code.

The Rust Programming Language · Ch.3 Common Programming Concepts

56

Chapter 3 · 3.5 Control Flow

Running the branches program

Try running this code; you should see the following output:

$ cargo run

   Compiling branches v0.1.0 (file:///projects/branches)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s

     Running `target/debug/branches`

condition was true

Because number is 3, the condition number < 5 is true and the first arm runs.

Next, let’s change the value of number to a value that makes the condition false (the next slide sets it to 7), run the program again, and look at the output.

The Rust Programming Language · Ch.3 Common Programming Concepts

57

Chapter 3 · 3.5 Control Flow

Making the condition false

fn main() {

    let number = 7;

 

    if number < 5 {

        println!("condition was true");

    } else {

        println!("condition was false");

    }

}

$ cargo run

   Compiling branches v0.1.0 (file:///projects/branches)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s

     Running `target/debug/branches`

condition was false

The Rust Programming Language · Ch.3 Common Programming Concepts

58

Chapter 3 · 3.5 Control Flow

The condition must be a bool

It’s also worth noting that the condition in this code must be a bool. If the condition isn’t a bool, we’ll get an error. For example, try running the following code:

src/main.rs

fn main() {

    let number = 3;

 

    if number {

        println!("number was three");

    }

}

The if condition evaluates to a value of 3 this time, and Rust throws an error (next slide).

The Rust Programming Language · Ch.3 Common Programming Concepts

59

Chapter 3 · 3.5 Control Flow

Error: expected bool, found integer

$ cargo run

   Compiling branches v0.1.0 (file:///projects/branches)

error[E0308]: mismatched types

 --> src/main.rs:4:8

  |

4 |     if number {

  |        ^^^^^^ expected `bool`, found integer

 

For more information about this error, try `rustc --explain E0308`.

error: could not compile `branches` (bin "branches") due to 1 previous error

The error indicates that Rust expected a bool but got an integer. Unlike languages such as Ruby and JavaScript, Rust will not automatically try to convert non-Boolean types to a Boolean. You must be explicit and always provide if with a Boolean as its condition.

The Rust Programming Language · Ch.3 Common Programming Concepts

60

Chapter 3 · 3.5 Control Flow

Comparing explicitly against zero

If we want the if code block to run only when a number is not equal to 0, for example, we can change the if expression to the following:

src/main.rs

fn main() {

    let number = 3;

 

    if number != 0 {

        println!("number was something other than zero");

    }

}

Running this code will print number was something other than zero.

The Rust Programming Language · Ch.3 Common Programming Concepts

61

Chapter 3 · 3.5 Control Flow

Handling multiple conditions with else if

You can use multiple conditions by combining if and else in an else if expression. For example:

src/main.rs

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");

    }

}

The Rust Programming Language · Ch.3 Common Programming Concepts

62

Chapter 3 · 3.5 Control Flow

Only the first true branch runs

This program has four possible paths it can take. After running it, you should see the following output:

$ cargo run

   Compiling branches v0.1.0 (file:///projects/branches)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s

     Running `target/debug/branches`

number is divisible by 3

When this program executes, it checks each if expression in turn and executes the first body for which the condition evaluates to true. Even though 6 is divisible by 2, we don’t see number is divisible by 2, nor the number is not divisible by 4, 3, or 2 text from the else block. Rust only executes the block for the first true condition, and once it finds one, it doesn’t even check the rest.

Remark. Using too many else if expressions can clutter your code, so if you have more than one, you might want to refactor your code. Chapter 6 describes a powerful Rust branching construct called match for these cases.

The Rust Programming Language · Ch.3 Common Programming Concepts

63

Chapter 3 · 3.5 Control Flow

Using if in a let statement

Because if is an expression, we can use it on the right side of a let statement to assign the outcome to a variable, as in Listing 3.2.

Listing 3.2: Assigning the result of an if expression to a variable — src/main.rs

fn main() {

    let condition = true;

    let number = if condition { 5 } else { 6 };

 

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

}

The number variable will be bound to a value based on the outcome of the if expression. The next slide runs this code to see what happens.

The Rust Programming Language · Ch.3 Common Programming Concepts

64

Chapter 3 · 3.5 Control Flow

Both arms must have the same type

Running Listing 3.2:

$ cargo run

   Compiling branches v0.1.0 (file:///projects/branches)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s

     Running `target/debug/branches`

The value of number is: 5

Remember that blocks of code evaluate to the last expression in them, and numbers by themselves are also expressions. In this case, the value of the whole if expression depends on which block of code executes. This means the values that have the potential to be results from each arm of the if must be the same type; in Listing 3.2, the results of both the if arm and the else arm were i32 integers.

If the types are mismatched, as in the example on the next slide, we’ll get an error.

The Rust Programming Language · Ch.3 Common Programming Concepts

65

Chapter 3 · 3.5 Control Flow

Arms with mismatched types

src/main.rs

fn main() {

    let condition = true;

 

    let number = if condition { 5 } else { "six" };

 

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

}

When we try to compile this code, we’ll get an error. The if and else arms have value types that are incompatible, and Rust indicates exactly where to find the problem in the program (next slide).

The Rust Programming Language · Ch.3 Common Programming Concepts

66

Chapter 3 · 3.5 Control Flow

The incompatible types error

$ cargo run

   Compiling branches v0.1.0 (file:///projects/branches)

error[E0308]: `if` and `else` have incompatible types

 --> src/main.rs:4:44

  |

4 |     let number = if condition { 5 } else { "six" };

  |                                 -          ^^^^^ expected integer, found `&str`

  |                                 |

  |                                 expected because of this

 

For more information about this error, try `rustc --explain E0308`.

error: could not compile `branches` (bin "branches") due to 1 previous error

The if block evaluates to an integer and the else block to a string. That won’t work: variables must have a single type, and Rust needs to know definitively at compile time what type number is, so it can verify the type is valid everywhere number is used. If the type were only determined at runtime, the compiler would be more complex and would make fewer guarantees about the code, having to track multiple hypothetical types for any variable.

The Rust Programming Language · Ch.3 Common Programming Concepts

67

Chapter 3 · 3.5 Control Flow

Repetition with loops

It’s often useful to execute a block of code more than once. To experiment with loops, make a new project called loops.

Definition 3.27 (Loop). A construct that runs through the code inside the loop body to the end and then starts immediately back at the beginning. Rust has three kinds of loops: loop, while, and for.

Repeating code with loop

The loop keyword tells Rust to execute a block of code over and over again, either forever or until you explicitly tell it to stop. As an example, change src/main.rs in your loops directory to look like this:

fn main() {

    loop {

        println!("again!");

    }

}

The Rust Programming Language · Ch.3 Common Programming Concepts

68

Chapter 3 · 3.5 Control Flow

Interrupting an endless loop

When we run this program, we’ll see again! printed over and over continuously until we stop the program manually. Most terminals support the keyboard shortcut ctrl-C to interrupt a program that is stuck in a continual loop. Give it a try:

$ cargo run

   Compiling loops v0.1.0 (file:///projects/loops)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s

     Running `target/debug/loops`

again!

again!

again!

again!

^Cagain!

The symbol ^C represents where you pressed ctrl-C. You may or may not see the word again! printed after the ^C, depending on where the code was in the loop when it received the interrupt signal.

The Rust Programming Language · Ch.3 Common Programming Concepts

69

Chapter 3 · 3.5 Control Flow

break, continue, and values from loops

  • Rust also provides a way to break out of a loop using code: place the break keyword within the loop to tell the program when to stop executing it. The guessing game did this in “Quitting After a Correct Guess” (Chapter 2) to exit when the user guessed the correct number.
  • The guessing game also used continue, which in a loop tells the program to skip over any remaining code in this iteration of the loop and go to the next iteration.

Returning values from loops

One use of a loop is to retry an operation you know might fail, such as checking whether a thread has completed its job. You might also need to pass the result of that operation out of the loop to the rest of your code. To do this, add the value you want returned after the break expression you use to stop the loop; that value will be returned out of the loop so you can use it, as the next slide shows.

The Rust Programming Language · Ch.3 Common Programming Concepts

70

Chapter 3 · 3.5 Control Flow

Returning a value with break

fn main() {

    let mut counter = 0;

 

    let result = loop {

        counter += 1;

 

        if counter == 10 {

            break counter * 2;

        }

    };

 

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

}

Before the loop, we declare counter and initialize it to 0. Then we declare result to hold the value returned from the loop. On every iteration, we add 1 to counter and check whether it equals 10. When it does, we use break with the value counter * 2. After the loop, a semicolon ends the statement that assigns the value to result. Finally, we print result, which in this case is 20.

Remark. You can also return from inside a loop. While break only exits the current loop, return always exits the current function.

The Rust Programming Language · Ch.3 Common Programming Concepts

71

Chapter 3 · 3.5 Control Flow

Disambiguating with loop labels

If you have loops within loops, break and continue apply to the innermost loop at that point.

Definition 3.28 (Loop label). An optional name on a loop, which you can then use with break or continue to specify that those keywords apply to the labeled loop instead of the innermost loop. Loop labels must begin with a single quote.

The example on the next slide has two nested loops:

  • The outer loop has the label 'counting_up, and it counts up from 0 to 2.
  • The inner loop, without a label, counts down from 10 to 9.
  • The first break, which doesn’t specify a label, exits the inner loop only.
  • The break 'counting_up; statement exits the outer loop.

The Rust Programming Language · Ch.3 Common Programming Concepts

72

Chapter 3 · 3.5 Control Flow

Nested loops with a label

src/main.rs (lines 1–11)

fn main() {

    let mut count = 0;

    'counting_up: loop {

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

        let mut remaining = 10;

 

        loop {

            println!("remaining = {remaining}");

            if remaining == 9 {

                break;

            }

src/main.rs (continued, lines 12–21)

            if count == 2 {

                break 'counting_up;

            }

            remaining -= 1;

        }

 

        count += 1;

    }

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

}

The Rust Programming Language · Ch.3 Common Programming Concepts

73

Chapter 3 · 3.5 Control Flow

Output of the labeled loops

This code prints:

$ cargo run

   Compiling loops v0.1.0 (file:///projects/loops)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.58s

     Running `target/debug/loops`

count = 0

remaining = 10

remaining = 9

count = 1

remaining = 10

remaining = 9

count = 2

remaining = 10

End count = 2

When count is 2, the inner loop’s break 'counting_up; exits the outer loop directly, so remaining = 9 is never printed in that pass.

The Rust Programming Language · Ch.3 Common Programming Concepts

74

Chapter 3 · 3.5 Control Flow

Streamlining conditional loops with while

A program will often need to evaluate a condition within a loop. While the condition is true, the loop runs. When the condition ceases to be true, the program calls break, stopping the loop. It’s possible to implement behavior like this using a combination of loop, if, else, and break; you could try that now in a program, if you’d like.

However, this pattern is so common that Rust has a built-in language construct for it.

Definition 3.29 (while loop). A loop that runs its body while a condition evaluates to true, and exits the loop otherwise.

In Listing 3.3 (next slide), we use while to loop the program three times, counting down each time, and then, after the loop, to print a message and exit.

The Rust Programming Language · Ch.3 Common Programming Concepts

75

Chapter 3 · 3.5 Control Flow

A while countdown

Listing 3.3: Using a while loop to run code while a condition evaluates to true — src/main.rs

fn main() {

    let mut number = 3;

 

    while number != 0 {

        println!("{number}!");

 

        number -= 1;

    }

 

    println!("LIFTOFF!!!");

}

This construct eliminates a lot of nesting that would be necessary if you used loop, if, else, and break, and it’s clearer. While a condition evaluates to true, the code runs; otherwise, it exits the loop.

The Rust Programming Language · Ch.3 Common Programming Concepts

76

Chapter 3 · 3.5 Control Flow

Looping through a collection with while

You can choose to use the while construct to loop over the elements of a collection, such as an array. The loop in Listing 3.4 prints each element in the array a.

Here, the code counts up through the elements in the array. It starts at index 0 and then loops until it reaches the final index in the array (that is, when index < 5 is no longer true).

Listing 3.4: Looping through each element of a collection using a while loop — src/main.rs

fn main() {

    let a = [10, 20, 30, 40, 50];

    let mut index = 0;

 

    while index < 5 {

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

 

        index += 1;

    }

}

The Rust Programming Language · Ch.3 Common Programming Concepts

77

Chapter 3 · 3.5 Control Flow

Running the while loop over the array

Running this code will print every element in the array:

$ cargo run

   Compiling loops v0.1.0 (file:///projects/loops)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.32s

     Running `target/debug/loops`

the value is: 10

the value is: 20

the value is: 30

the value is: 40

the value is: 50

All five array values appear in the terminal, as expected. Even though index will reach a value of 5 at some point, the loop stops executing before trying to fetch a sixth value from the array.

The Rust Programming Language · Ch.3 Common Programming Concepts

78

Chapter 3 · 3.5 Control Flow

Looping through a collection with for

However, the while approach is error-prone: we could cause the program to panic if the index value or test condition is incorrect. For example, if you changed the definition of the a array to have four elements but forgot to update the condition to while index < 4, the code would panic. It’s also slow, because the compiler adds runtime code to perform the conditional check of whether the index is within the bounds of the array on every iteration through the loop.

As a more concise alternative, you can use a for loop and execute some code for each item in a collection:

Listing 3.5: Looping through each element of a collection using a for loop — src/main.rs

fn main() {

    let a = [10, 20, 30, 40, 50];

 

    for element in a {

        println!("the value is: {element}");

    }

}

The Rust Programming Language · Ch.3 Common Programming Concepts

79

Chapter 3 · 3.5 Control Flow

Why for is the most common loop

  • Running Listing 3.5 gives the same output as Listing 3.4.
  • More importantly, it increases the safety of the code and eliminates the chance of bugs from going beyond the end of the array or not going far enough and missing some items.
  • Machine code generated from for loops can be more efficient as well, because the index doesn’t need to be compared to the length of the array at every iteration.
  • If you changed the number of values in the array, you wouldn’t need to remember to change any other code, as you would with Listing 3.4.

The safety and conciseness of for loops make them the most commonly used loop construct in Rust. Even when you want to run some code a certain number of times, as in the countdown of Listing 3.3, most Rustaceans would use a for loop, with a Range.

Definition 3.30 (Range). A type provided by the standard library that generates all numbers in sequence, starting from one number and ending before another number.

The Rust Programming Language · Ch.3 Common Programming Concepts

80

Chapter 3 · 3.5 Control Flow

A for countdown over a range

Here’s what the countdown would look like using a for loop and another method not yet discussed, rev, to reverse the range:

src/main.rs

fn main() {

    for number in (1..4).rev() {

        println!("{number}!");

    }

    println!("LIFTOFF!!!");

}

This code is a bit nicer, isn’t it?

Example 3.31. 1..4 is the range 1, 2, 3 (it ends before 4); .rev() walks it as 3, 2, 1, so the program prints 3!, 2!, 1! and then LIFTOFF!!! — the same countdown as Listing 3.3.

The Rust Programming Language · Ch.3 Common Programming Concepts

81

Chapter 3 · Summary

Chapter summary

You made it! This was a sizable chapter: you learned about variables, scalar and compound data types, functions, comments, if expressions, and loops.

To practice with the concepts discussed in this chapter, try building programs to do the following:

  • Convert temperatures between Fahrenheit and Celsius.
  • Generate the nth Fibonacci number.
  • Print the lyrics to the Christmas carol “The Twelve Days of Christmas”, taking advantage of the repetition in the song.

Remark. When you’re ready to move on, Chapter 4 covers a concept in Rust that doesn’t commonly exist in other programming languages: ownership.

The Rust Programming Language · Ch.3 Common Programming Concepts

82