Preface
This is my endeavour to learn Rust properly. How? I’ll be following these two resources:
- The Book
- Debugging Exercises
- Rustlings exercises // Note I’ll be learning this on Linux but Rust is also available on Mac and Windows.
Comp4959 Notion notes
Comp4959 was part Rust and part Elixir, but the majority of the notes from the earlier lectures cover rust. Check out the Notion notes online here or locally: Notes:
- COMP4959-Lec.1 - Introduction
- COMP4959-Lec.2 - File IO, Errors, and Structs
- COMP4959 - Strings]
- COMP4959-Lec.3 - Closures, Enums, and Iterators]
- COMP4959-Lec.4 - Web Assembly and Traits
Before we begin
crates.io
This is where all the crates created by the Rust community can be found and installed, Cargo automatically fetches the latest versions of a crate when used. https://crates.io/
Installing Rust
I’m not gonna tell ya how, read the docs.
Updating
rustup update
Uninstalling
rustup self uninstall
Local Documentation
Rust includes a local copy of all the docs that you can read in the browser (even without an internet connection) by simply using the command rustup doc
.
Intro
Rust aims to balance between high-level ergonomics and low-level control by setting the compiler as a gate-keeper of sorts that will prevent compiling the program due to the elusive bugs and pitfalls associated with memory management and concurrency. Rust values speed and stability so it’s great for everything from Web apps to embedded software including OperatingSystems.
Features
- Cargo is Rust’s dependency manager and build tool, it makes adding, compiling, and managing dependencies easy and “painless”.
- Rustfmt is its formatting tool that ensures a consistent coding style across the community. Many IDEs use rust-analyzer to integrate code-completion and inline error-messages. I will be using Jetbrains’ RustRover.
Hello World
As tradition ordains, our first program is a HelloWorld program. Rust doesn’t dictate where our code lives nor what editor or IDE we use, so structure your projects and files however works for you. Remember that this language is a CompiledLanguage so we’ll need to compile them.
Steps
- To create a Rust source file named
main.rs
Note
Rust uses “snake_case” convention to separate words in filenames. E.g
hello_world.rs
and nothelloworld.rs
!
- Using your editor of choice type out:
fn main() {
println!("Hello, World!");
}
- To compile it
rustc main.rs
- Then run the executable
./main
- “Hello, World!” will print into your console. Breakdown
- A Rust source file’s entry point is the
main
function, it’s the first code that runs whenever a Rust executable is ran. - Rust functions are wrapped in curly braces
{}
like many popular ProgrammingLanguages. - Parameters go into parenthesis
()
that follow the function’s name, also common. - The one line
println!("Hello, World!");
is an example of Macro in Rust. - Line ends in
;
, indicating this expression is over. Most lines of code in Rust end in a semicolon. - The function returns nothing.
Rust Macros
RustMacros are denoted with the !
that succeeds the macro’s name, these will be expanded upon later in the book (Ch. 20) but for now know that they’re not ordinary functions and don’t follow the rules normal functions do.
Compiling and Running
As mentioned before Rust is a CompiledLanguage similar to many others, most commonly C/C++. So before every time you run a program you must compile it, this is where the gate-keeper Ferris (Rust’s crab mascot) comes in to check your work. If Ferris is happy, then you can run the executable according to how that’s done in your OS of choice.
Intro to Cargo
Use Cargo to manage packages and dependencies in your programs. Cargo will also build your projects when the time comes.
Rust refers to packages as Dependencies.
Cargo comes with every installation of Rust, so it’s safe to assume you have. Check cargo --version
.
Creating a project
Cargo can be used to create projects using the command cargo new project_name
.
Once a project is created you’ll notice:
- A
src
directory for your code. - A
Cargo.toml
file. - It’ll also initialise a Git repo with a
.gitignore
file for convenience. This won’t happen in an existing Git repo, and can be overridden usingcargo new --vcs=git
.
Info
To see what options exist for Cargo commands, try
cargo <command_name> --help
.
Inside Cargo.toml
you’ll find something like:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2024"
[dependencies]
More on TOML files.
Description:
-
The first line,
[package]
, is a section heading indicating a package’s configuration. More sections can be added as more info is needed. -
Lines 2-4 set the configuration information Cargo needs to compile your program: the name, the version, and the edition of Rust to use. The
edition
key is expanded upon in Appendix E. -
The last line,
[dependencies]
, is the section listing a project’s dependencies AKA Crates. In Rust, packages of code are referred to as crates. -
Cargo will also make a Hello world function in
src/main.rs
automatically for new projects. -
Cargo expects all source files in the
src
directory, leaving the root for README files, license information, configuration files, and anything not code related.
Converting a directory to a Cargo project
To convert a project that doesn’t use Cargo:
- Move the code to
/src
. - Create appropriate
Cargo.toml
file usingCargo init
command. - Done.
Building and running projects
To build a project cargo build
which creates an executable file in target/debug/project_name
.
The run the binary using ./target/debug/project_name
.
Whenever a project is built a Cargo.lock
file is generated in the root directory which tracks the exact versions of dependencies in your project.
To combine the two steps into one simply run cargo run
.
// Cargo doesn't rebuild a project if no changes were made!
Important: To check our code compiles without producing an executable, use the cargo check
command, this is better and faster than always rebuilding and recompiling ever time you make a change! So it’s a good habit to run this frequently as you work on your project.
Building for release
When the time’s ready and you’re about to release your project, run cargo build --release
to build it with optimizations for production.
- Create an executable in
target/release
instead oftarget/debug
. - Makes code run faster, but these optimizations take longer than building for development.
When benchmarking code runtime, always build for release first!
Cargo as a convention
Cargo doesn’t have many advantages in small projects like Hello, World
but it’s the convention among the community and is good to cultivate the habit and get used to the workflow.