13 Feb 2021

Rust Basics (1)

The goal of this post is to learn how to install the necessary tools to program in Rust, compile a minimal example and learn the basics of Cargo.

The following instructions are valid for Linux or macOS. For Windows, please refer to the Rust documentation.

Installation

To install rustup:

curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

Once installed, Rust set of tools can be updated with:

rustup update

Or can be removed with:

rustup self uninstall

Hello world

It’s time for the first program in Rust!

Let’s create our working directory first:

mkdir hello_world
cd hello_world

Then create a source file called main.rs:

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

It’s possible to compile the code with:

rustc main.rs

And execute the binary:

./main

The following is expected:

Hello, world!

Cargo

Cargo is Rust’s package manager. To check the installed version:

cargo --version

To create a new project with Cargo, just enter:

cargo new hello_world

The command creates the project tree, initializes the Git repository with .gitignore, adds the TOML config file Cargo.toml and populates the src directory with a minimal hello_world source code.

Essential commands:

cmd desc
cargo build Build the project (unoptimized + debug)
cargo run Run the project (after compiling if necessary)
cargo check Ensure that the source code compiles

To build the optimized/release target, enter:

cargo build --release

Reference

Material for this post is available on GitHub.

More infos on the Rust documentation.

Go to the next post of the serie.


Tags: