Learn Rust · 1/14

Welcome to Rust: Setup and First Steps

8 min read

Hey there, future Rustacean! Welcome to your first step into the world of Rust. Think of this guide as your friendly neighborhood helper, here to get you started on your journey. We'll go from "Why even bother with Rust?" to you writing and running your very own program. Let's get this adventure started! 🚀

The Why Before the How: Why Rust? 🦀

Before we get our hands dirty with code, let's talk about why you'd want to learn Rust in the first place. It's not just another programming language; it's a tool designed to solve some of the peskiest problems in software development.

The Problem: For a long time, developers faced a tough choice. On one hand, you have languages like C++ that are super fast and give you a lot of control over the computer's memory. This is great for performance but also makes it easy to introduce nasty bugs related to memory, like crashes and security vulnerabilities. On the other hand, you have languages like Python and Java that are safer because they manage memory for you (using something called a garbage collector), but this safety can come at the cost of performance.

Rust's Solution: Rust swoops in to give you the best of both worlds: the speed and control of a low-level language with the safety and modern features of a high-level one. It achieves this through a unique "ownership" system that manages memory at compile time, meaning memory-related bugs are caught before your program even runs. This lets you write fast, reliable software without pulling your hair out over memory management.

In a Nutshell, Rust Offers:

  • Performance: Rust is blazingly fast and memory-efficient. With no runtime or garbage collector, it's perfect for performance-critical services, running on embedded devices, and easily integrating with other languages.
  • Reliability: Rust's type system and ownership model guarantee memory safety and thread safety, helping you eliminate many types of bugs at compile-time.
  • Productivity: It comes with great documentation, a helpful compiler with clear error messages, and excellent tooling.

Fun Fact: The inspiration for Rust came from a broken elevator! A Mozilla developer, Graydon Hoare, started Rust as a personal project in 2006 after getting frustrated with the elevator software in his apartment building crashing. He realized these crashes often stemmed from memory issues in languages like C++. The name "Rust" is said to be inspired by a type of robust fungi that is "over-engineered for survival."

And who's that crab you see everywhere? That's Ferris, the unofficial mascot of the Rust community. Many Rust programmers call themselves "Rustaceans," a play on the word "crustacean."

Setting up the Toolchain: rustup, rustc, and cargo

Alright, enough talk! Let's get your computer ready to write some Rust. The main tool we'll use is rustup, the official Rust toolchain installer.

Installation

The recommended way to install Rust is by using rustup.

For Linux and macOS:

Open your terminal and run the following command:

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

This command downloads and runs a script that will install the latest stable version of Rust. You might be asked for your password during the installation.

For Windows:

Head over to the official Rust website at https://www.rust-lang.org/tools/install and follow the instructions. You'll download and run rustup-init.exe. The installer will also help you set up any necessary prerequisites, like the Visual Studio C++ build tools.

After the installation is complete, it's a good idea to restart your terminal. To verify that everything is working, open a new terminal and type:

bash
rustc --version

You should see the version number, commit hash, and commit date of the Rust compiler.

The Holy Trinity of Rust Tooling

When you install Rust with rustup, you get a few key command-line tools. Let's break them down:

  • rustc (The Compiler): This is the heart of the Rust ecosystem. Its job is to take your Rust code and turn it into a runnable program. You can use it directly to compile your files.
  • cargo (The Package Manager & Build System): Think of cargo as your project manager. It handles a ton of tasks for you, like creating new projects, downloading libraries (which are called "crates" in Rust), building your project, and running it. In the JavaScript world, it's similar to npm or yarn.
  • rustup (The Toolchain Manager): This tool manages your Rust installations. It allows you to easily switch between different versions of Rust (like stable, beta, and nightly builds) and keep them updated.

In practice, you'll mostly be interacting with cargo. It calls rustc for you with all the right settings, so you don't have to worry about the nitty-gritty details.

Your First Rust Program: Hello, World!

It's a time-honored tradition in programming to start with a "Hello, World!" program. Let's create ours!

The Old-Fashioned Way (with rustc)

First, let's see how to compile and run a simple Rust program using just the compiler.

  1. Create a file: Create a new file named main.rs. The .rs extension is for Rust files. It's a convention to use underscores for multiple words in filenames, like hello_world.rs.

  2. Write the code: Open main.rs in a text editor and add the following code:

    rust
    fn main() {
        println!("Hello, world!");
    }
  3. Compile and Run: Now, head to your terminal, navigate to the directory where you saved main.rs, and run these commands:

    On Linux or macOS:

    bash
    rustc main.rs
    ./main

    On Windows:

    bash
    rustc main.rs
    .\main.exe

You should see "Hello, world!" printed to your terminal. Congratulations, you're officially a Rust programmer!

Breaking Down the Code:

  • fn main() { ... }: This defines a function named main. The main function is special; it's always the first code that runs in an executable Rust program.
  • println!("Hello, world!");: This line does the printing. You'll notice the !. This means we're calling a Rust macro, not a regular function. We'll dive into what macros are later, but for now, just know that println! is how you print text to the console.
  • ;: The semicolon marks the end of the statement.

The Modern Way (with cargo)

While using rustc directly is good to know, for any real project, you'll want to use cargo.

Let's create the same "Hello, World!" program, but this time with cargo.

  1. Create a new project: In your terminal, run:

    bash
    cargo new hello_cargo

    This command creates a new directory called hello_cargo with all the necessary files to get started.

  2. Explore the project: If you look inside the hello_cargo directory, you'll see a src folder with a main.rs file already containing the "Hello, World!" code. You'll also find a Cargo.toml file.

  3. Run the project: Navigate into the new directory and run:

    bash
    cargo run

    This command will compile and then run your project. You'll see the "Hello, world!" output again.

Notice how much simpler that was? cargo handles the compilation and execution in one step. It also organizes your project files neatly.

Cargo Deep Dive: The Rust Package Manager

cargo is your best friend when working with Rust. Let's take a closer look at what it does and some of the most common commands.

The Cargo.toml File

The Cargo.toml file is the configuration file for your project. It's written in the TOML (Tom's Obvious, Minimal Language) format. This file is where you'll put metadata about your project and list any external libraries (crates) you want to use.

A basic Cargo.toml file looks like this:

toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"

[dependencies]
  • [package]: This section contains information about your package, like its name, version, and the Rust edition it uses.
  • [dependencies]: This is where you'll list the crates from crates.io (the Rust package registry) that your project depends on.

Frequently Used Cargo Commands

Here are some of the cargo commands you'll be using all the time:

  • cargo new <project_name>: Creates a new Rust project with a standard directory structure.
  • cargo build: Compiles your project. The resulting executable will be in the target/debug directory.
  • cargo build --release: Compiles your project with optimizations for performance. The executable will be in target/release.
  • cargo run: Compiles and runs your project.
  • cargo check: Quickly checks your code to make sure it compiles, but doesn't produce an executable. This is much faster than a full build and great for checking for errors as you code.
  • cargo clean: Removes the target directory, cleaning up all the build artifacts.
  • cargo update: Updates the dependencies listed in your Cargo.toml file to their latest versions.
  • cargo add <crate_name>: A convenient way to add a new dependency to your Cargo.toml file.

There are many more cargo commands and a whole ecosystem of installable subcommands, but these are the ones you'll use daily.


And that's a wrap for your first foray into Rust! You've learned why Rust is such a compelling language, set up your development environment, written your first program, and gotten acquainted with the mighty cargo. You're well on your way to becoming a proficient Rustacean. Keep building! 🦀

📚 Extra Reading

Challenge

Task

Write a complete Rust program from scratch that serves as the entry point for an application. The program must print two specific, separate lines to the standard output.

Requirements

  1. Define the main function, which is the entry point of every executable Rust program.
  2. Inside the main function, use the println! macro to output text.
  3. The first line printed must be exactly: Initializing Rust project...
  4. The second line printed must be exactly: Compiler: rustc, Build Tool: cargo
  5. Ensure each message is printed on a new line.

Expected result

Your code must be a complete and valid Rust program that, when compiled and executed, would produce the following two lines of output in the console. The order and content must match exactly.

text
Initializing Rust project...
Compiler: rustc, Build Tool: cargo
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.