Learn › Rust Programming

Introduction to Rust

Discover why Rust exists, set up your toolchain with Cargo, and write your first Rust program.

Why Rust?

Rust is a systems programming language focused on safety, speed, and concurrency. It achieves memory safety without a garbage collector through its innovative ownership system, which catches memory errors at compile time rather than at runtime. Rust has been voted the most loved programming language in the Stack Overflow survey for multiple consecutive years. It is used in production by companies like Mozilla, Microsoft, Amazon, and Google for performance-critical infrastructure.

Installing Rust and Cargo

The recommended way to install Rust is through rustup, the official toolchain manager. Rustup installs the Rust compiler, the standard library, and Cargo, which is Rust's build system and package manager. Cargo handles compiling your code, downloading dependencies, building documentation, and running tests. It is the central tool in the Rust ecosystem and you will use it for nearly every Rust project.

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

# Verify installation
rustc --version
cargo --version

# Create a new project
cargo new hello_rust
cd hello_rust

Hello, World!

Every Rust program begins with a main function, which is the entry point of the executable. The println! macro prints text to the console, with the exclamation mark indicating that it is a macro rather than a regular function. Rust files use the .rs extension and are compiled with rustc or more commonly through Cargo. The fn keyword declares a function, and Rust uses curly braces to delimit blocks just like C and C++.

fn main() {
    println!("Hello, World!");

    // Variables and string formatting
    let name = "Rust";
    let version = 2024;
    println!("Welcome to {} in {}!", name, version);

    // Multi-line printing
    println!(
        "Rust provides:\n  - Memory safety\n  - Zero-cost abstractions\n  - Fearless concurrency"
    );
}

Building with Cargo

Cargo manages your project structure, dependencies, and build process. The Cargo.toml file is the manifest that describes your project's metadata and its dependencies. Running cargo build compiles your project, cargo run compiles and runs it, and cargo test runs your test suite. Cargo also integrates with crates.io, the Rust community's package registry, making it simple to add third-party libraries to your project.

# Build the project
cargo build

# Build and run
cargo run

# Build with optimizations for release
cargo build --release

# Run tests
cargo test

# Check code without producing a binary (faster)
cargo check

Variables & Mutability →