shagag
Frontend Engineer
by shagag

Rust - Getting Started

01/03/2025

word count:397

estimated reading time:2 minutes

Note

The following is my notes taken while reading The Rust Programming Language by Steve Klabnik and Carol Nichols, which was recommended to me by the awesome Rust community. I preferred to go over a book and not the online one, because once it’s on my desk and I don’t open it, I feel ashamed and have to open it 🥲 I call it self-shaming manipulation to do the damn work

Let’s create the famous (or infamous, depends on who you are) Hello, World program:

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

The main function is always the first code that runs in every executable Rust program.

rustc main.rs

The line above calls the rust compiler to compile the main.rs file.

Hello, Cargo

Cargo is Rust’s build system and package manager.

Creating a project with cargo:

cargo new hello_cargo
cd hello_cargo

This should generate a project with several files: Cargo.toml:

[package] # the following statements are configuring a package
name = "hello_cargo" # name of the packagae
version = "0.1.0" # version
edition = "2021" # the edition of rust

[dependencies] # section of deps

In Rust, packages of code are referred to as crates

src/main.rs:

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

Cargo expects your source files to live inside the src directory, the top level directory is just for README files, license information, configuration files, and anything else not related to your code.

Building and Running a Cargo project:

cargo build
./target/debug/hello_cargo -> Hello, world!

cargo build also creates a new file at the top level: Cargo.lock:

# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3

[[package]]
name = "hello_cargo"
version = "0.1.0"

This file keeps track of the exact versions of dependencies in your project.

Summary of cargo commands:

Building for Release

When your project is ready to be released, you should use the cargo build --release to compile it with optimizations, this command will create an executable inside target/release folder.