Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Course 1: Rust Language

Rust Introduction: Cargo, Crates, Rust project, Hello World (2h on computers)

Pierre Cochard, Tanguy Risset

This course has been set up for students of the Telecommunication Department at INSA-Lyon (5th year), it is vastly inspired by the Rust book and many other resources on the web. It assumes that students do not have any programming experience in Rust, but have a strong programming experience in other languages (C/C++ and object-oriented languages in particular).

In addition to these documents, some others are available on Moodle https://moodle.insa-lyon.fr/course/view.php?id=10386, presenting the concepts covered in this course. Don’t forget to check it before you start. Many of the information listed here come from https://www.rust-lang.org/learn/.

The course is organized in sections that have questions. In addition, you will find text boxes labeled Course:, in which important concepts are presented.

Course: What is Rust and Why Rust

Why should computer science engineers always learn new languages?

The use of the Rust programming language is growing exponentially, the number of useful libraries and projects that are available to developers is already huge. The main reason for that is that Rust provides safe memory management without a garbage collector, ensuring both performance and security. Its ownership system eliminates data races and segmentation faults. It enables efficient and concurrent programming while guaranteeing memory safety. It is associated with a powerful modern ecosystem and is suited for embedded systems, system programming as well as high-performance applications. Adopted by major industry players, Rust is emerging as a reliable alternative for secure and system-level development.

Setting up the environment for using Rust

We’re going to start by setting up the environment that will enable you to program in Rust. We recommend that you use Rust on your own machine, but the environment is already installed on the department computers.

This environment simply consists in having:

  1. An editor for programming, we strongly recommend Visual Studio Code that is available on all OS, for instance here: https://code.visualstudio.com/ (not to be confused with Visual Studio, which is a different program). Together with the rust-analyzer extension. See the Appendix below for an introduction to Visual Studio Code.

  2. Install both the rust compiler (rustc) and cargo, with the rustup installer script.

cargo is Rust’s package manager and build system. Its installation and versioning are managed by rustup.

Below is a summary for installing Rust and cargo on your laptop. The original complete instructions can be found here: https://doc.rust-lang.org/book/ch01-01-installation.html.

As a summary:

  • On linux, use the following command:

    curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
    
  • On (recent) macOS:

1) curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh -s -- --no-modify-path

2) Choose 1)

3) . "$HOME/.cargo/env"

4) rustc --version
    cargo --version

  • On Windows (detailed instructions below).

Installing Rust on Windows

On Windows, Rust uses by default the Microsoft C++ build tools (MSVC) to link programs (i.e. to produce the final .exe file). They are not installed with Rust itself, but rustup can install them for you. Plan for a few GB of disk space and some download time.

  1. Go to https://www.rust-lang.org/tools/install and download rustup-init.exe (the 64-bit version on most laptops, or the ARM64 version on ARM laptops, e.g. Snapdragon-based).

  2. Run rustup-init.exe. A terminal window opens.

    • If the C++ build tools are not already installed, rustup warns you and proposes several options: choose 1) Quick install via the Visual Studio Community installer. The Visual Studio Installer then downloads and installs the required components (MSVC compiler/linker and the Windows SDK): wait for it to finish, close it, and go back to the rustup window.
    • rustup then displays the installation options: choose 1) Proceed with standard installation (default, just press Enter).
  3. When the installation is complete, close all your terminals and VS Code, and reopen them (the PATH environment variable has been modified, and is only read when a program starts).

  4. In a new terminal (PowerShell, or the VS Code terminal with Ctrl-J), check that everything works:

    rustc --version
    cargo --version
    
  5. Install the rust-analyzer extension in VS Code (see the Appendix).

Alternatively, if you use the winget package manager, you can install rustup with winget install Rustlang.Rustup, but you will then have to install the C++ build tools yourself (see below).

Common problems on Windows:

  • error: linker 'link.exe' not found when running cargo build or cargo run: the C++ build tools are missing. Download Build Tools for Visual Studio from https://visualstudio.microsoft.com/downloads/ (or open the Visual Studio Installer if it is already installed and click Modify), check the Desktop development with C++ workload (it includes MSVC and the Windows SDK), and install it.
  • 'cargo' is not recognized as an internal or external command (or cargo: The term 'cargo' is not recognized... in PowerShell): the terminal was opened before the installation. Close all terminals and VS Code windows and reopen them. If the problem persists, check that %USERPROFILE%\.cargo\bin is in your PATH (Settings → search for environment variables → Edit environment variables for your account).
  • rust-analyzer does not work in VS Code: restart VS Code completely after installing Rust.

Another option on Windows is to use WSL (Windows Subsystem for Linux): install it with wsl --install in an administrator PowerShell (and restart), then follow the Linux instructions above inside the WSL terminal. VS Code can work directly in WSL thanks to the WSL extension.

Whatever your OS, Rust can later be updated with rustup update.

Course: What is cargo used for?

cargo manages many aspects that you need to understand to use Rust correctly:

  • Dependency Management: Cargo manages the dependencies of a Rust project. It automatically downloads and builds the required libraries and dependencies, making it easier for developers to include external code in their projects.

  • Project Configuration: Cargo uses a file called Cargo.toml to configure a Rust project. This file includes information about the project, its dependencies, and various settings.

  • Building and Compilation: Cargo handles the compilation process of Rust code. It can build the project, manage dependencies, and generate executable binaries. Developers can use Cargo commands like cargo build to compile the project or cargo run to build and run it in one step.

  • Testing: Cargo provides built-in support for testing Rust code. Developers can use the cargo test command to run tests defined in the project.

  • Documentation: Cargo can generate and serve documentation for the project using the cargo doc command. This is useful for both internal and external documentation (the HTML file that you are reading has been generated by cargo doc)

  • Publishing Packages: Cargo facilitates the process of publishing Rust packages to the official package registry, called "Crates.io." This makes it easy for others to discover and use Rust libraries and projects.

Rust Hello World

A Rust project is contained in a directory which has the name of the project. From now on, we suggest making a project in your home directory and keeping all your Rust code there.

We will use the cargo command to build our first hello_world project. Note that this is not mandatory, everything can be built by hand, the Rust compiler can be invoked without cargo by using the command rustc.

Execute the following command:

cargo new hello_world

Check the generated files:

  • Cargo.toml is the project configuration file written in the TOML (Tom’s Obvious, Minimal Language) format1.
  • src/main.rs is the Rust main file (the program entrypoint).

Now, build your project with the cargo build command.

  • Where is the generated executable file?
  • What is the bang (!) after println?

Course: What about println!

As you can see on the Rust Standard Library documentation : println! is not a function, it is a macro.

Macros are called with a trailing bang (such as println!), they are a way of writing code that writes other code, which is known as metaprogramming. Understanding and declaring Macros is quite complex and will be seen later. But using them (for instance, println!) is usually very straightforward.

Course: About the code examples

The code examples in these TDs come in two forms:

  • Snippets without fn main(): a few statements illustrating a notion. Copy them inside the main function of your current project.
  • Complete programs with fn main(): they usually define items (functions, structs, use declarations…) before main. Copy them as a whole to replace the contents of src/main.rs (or of another file, e.g. src/bin/q4.rs, which can be run with cargo run --bin q4, see TD6).

Pasting a complete program into a file that already has a main function results in the error: “the name main is defined multiple times”.

Variables, Types and Mutability

Types in Rust

Rust is a statically typed language. scalar types are: integer types, floating point types, boolean and characters. Other types (i.e. compound types, slices or types defined by the user) will be introduced later.

The let keyword declares and initializes a variable, its type can be inferred by the compiler or stated explicitly:

#![allow(unused)]
fn main() {
let x: f32 = 2.0;
let y = 3; 
}

Integer Types in Rust

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

Literals (i.e. constant) in Rust

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

Floating points are f32 or f64.

Boolean type (bool) has only two values: true and false.

Characters are indicated with simple quotes: let c = 'z';. they are stored on 4 bytes, as unicode scalar values, but in String or string slices (&str), they are stored in UTF-8.

Mutability concept in Rust

By default, variables are immutable (i.e. once initialized, their value cannot be changed). You can make them mutable by adding mut in front of the variable name. A mutable variable must keep the same type forever.

What is the problem with the program below? Does it compile?

#![allow(unused)]
fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}

What are the values printed by the program below?

#![allow(unused)]
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 notion of scope is very important in Rust: it determines when values are freed and how long references remain valid. We will see it in more detail in TD2 (ownership, borrowing and lifetimes).

A first introduction to characters strings

For representing strings, Rust proposes two types: String and string slices (&str).

  • String is a powerful type, vector of UTF-8 bytes that can be muted, allocated on the heap.
  • &str is an immutable fat pointer (pointer + length) of UTF-8 bytes. It is often owned by something else: a String for instance.

For instance:

#![allow(unused)]
fn main() {
 let s = String::from("hello world");

   let hello = &s[0..5];
   let world = &s[6..11];
}
The example in memory (from Rust documentation, note the upper bound is one more that last element, array notation in Rust)

Functions in Rust

Functions in Rust have little difference with functions in other programming languages. They are declared with the fn keyword, and their parameters (arguments) are passed by value or reference.

Write a function fibonacci: fibonacci(n: i32) -> i32, which computes element n of the fibonacci sequence.

We will not use a recursive solution, but rather a for loop whose syntax will be: for i in 2..n+1 ( half-open range) and mutable variables.

We recall the definition of the fibonacci function fib:

fib(0)=1
fib(1)=1
fib(i)=fib(i-1)+fib(i-2)  for i >= 2

Flow Control in Rust

The most common constructs that let you control the flow of execution of Rust code are if expressions and loops.

If expressions

The syntax of if expression is quite intuitive (warning, no parenthesis around the condition)

fn main() {
    let number = 3;

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
}

The else part is optional, and can also be replaced by else if, hence handling multiple conditions.

If expressions can be used on the right side of a let statement.

Loops in Rust

The loop keyword can be used to create infinite loops, which can be interrupted by the breakkeyword.

#![allow(unused)]
fn main() {
  let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };
    println!("result: {result}");

}

The while construct is quite standard:

#![allow(unused)]
fn main() {
let mut number = 3;

    while number != 0 {
        println!("{number}!");

        number -= 1;
    }
}

The for loop in Rust is more specific. It is designed to iterate on an object that can be transformed into an iterator with the into_iter() method (i.e. objects that implement the IntoIterator trait). For instance, for loops can iterate over the element of an array.

#![allow(unused)]
fn main() {
    let a = [10, 20, 30, 40, 50];

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

The most common ranges (e.g. 0..10, 0..=10) can be used in loops because they implement the IntoIterator trait). The iter() method can be used to iterate over references to the elements of a collection, without consuming it:

fn main() {
    let v1 = vec![1, 2, 3];

    let v1_iter = v1.iter();

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

Appendix: Introduction to Visual Studio Code

Key Features of Visual Studio Code

Visual Studio Code stands out due to the following features:

  • Built-in support for multiple programming languages: VS Code supports a wide array of languages such as Python, JavaScript, C++, Java, and more, thanks to its extension system.

  • Extensions and customization: A vast library of extensions is available to add functionalities like debugging, version control, and language-specific tools.

  • Integrated debugger: VS Code provides an interactive debugging environment to simplify error correction in the code.

  • Version control integration: Seamless integration with Git and other version control systems allows developers to track code changes directly within the editor.

  • Integrated terminal: A terminal is available inside the editor, enabling command execution without leaving the application.

  • IntelliSense: This feature offers intelligent code completion and contextual suggestions based on syntax and variable types.

  • Cross-platform compatibility: VS Code works consistently on Windows, macOS, and Linux, ensuring a uniform user experience regardless of the operating system.

Thanks to its intuitive interface and powerful tools, Visual Studio Code has become one of the most popular editors among developers, whether they are beginners or experienced professionals. Its active community and frequent updates make it a reliable choice for addressing the evolving needs of software development.

How to use VS code efficiently for Rust

Installation with snap (Linux):

sudo snap install code --classic
  • Open the project directory:

    code myproject
    
  • Add the Rust Analyzer extension (left bar, small squares), search rust → install rust-analyzer

  • Go to Explorer

  • Ctrl-Shift-P: command palette

  • Ctrl-P: search for a file

  • Ctrl-Shift-E: explorer

  • Ctrl-J: command line inside VS Code

  • Ctrl-Shift-I: indent the whole Rust file

To compile:

  • Either use the Run button above main (Rust Analyzer)

  • Or Ctrl-Shift-P and type Run, then select

  • Or Ctrl-J and type:

    cargo build
    

  1. You can have more documentation about the TOML format here: https://toml.io/en/ or here in french: https://toml.io/fr/. However, it is probably not necessary, TOML is quite simple to understand. ↩