0 day streak
Code library

Beginner Rust exercises

Read these Beginner Rust snippets line by line — each one comes with a written breakdown of what the code does and why.

Rust · Beginner

Control Flow with If Expressions

In Rust, 'if' is an expression, not just a statement. This means it returns a value that can be assigned to a variable, provided all branches return the same type.

Control FlowSyntax
Open snippet →
Rust · Beginner

Working with Fixed-Size Arrays

Arrays in Rust have a fixed length and must contain elements of the same type. They are useful when you want your data allocated on the stack rather than the heap.

Arrays & ListsData Types
Open snippet →
Rust · Beginner

Variables and Immutability

In Rust, variables are immutable by default, meaning their value cannot change once bound. To allow a variable to be updated, you must explicitly use the 'mut' keyword.

SyntaxData Types
Open snippet →
Rust · Beginner

Basic Error Handling with Option

Rust uses the Option enum to represent a value that might be missing, instead of using null. 'match' is used to safely handle both the presence (Some) and absence (None) of the value.

Error HandlingData Types
Open snippet →
Rust · Beginner

Defining Basic Functions

Functions are declared using 'fn'. Parameters must have explicit type annotations, and the return type is specified after an arrow '->'. The last expression in a function is its return value.

FunctionsSyntax
Open snippet →
Rust · Beginner

Defining Basic Enums

Enums (enumerations) allow you to define a type by enumerating its possible variants. Variants can also hold data.

SyntaxData Types
Open snippet →
Rust · Beginner

Variables and Mutability in Rust

In Rust, variables are immutable by default. This means once you assign a value to a variable, you cannot change it. This is a powerful feature that helps prevent bugs. If you need to change a vari…

SyntaxData Types
Open snippet →
Rust · Beginner

Pattern Matching with Match

Rust's match expression is a powerful control flow tool that allows you to compare a value against a series of patterns and execute code based on which pattern matches. It is similar to switch stat…

Control FlowSyntax
Open snippet →
Rust · Beginner

Error Handling with Result Type

Rust uses the Result type for error handling without exceptions. Result is an enum with two variants: Ok(T) for success containing a value, and Err(E) for failure containing an error message. This…

Error HandlingFunctions
Open snippet →
Rust · Beginner

Understanding Ownership

Rust uses an ownership system to manage memory efficiently without garbage collection. When you assign s1 to s2, ownership of the data moves to s2, and s1 is no longer valid. This prevents double-f…

Memory ManagementBest Practices
Open snippet →
Rust · Beginner

Understanding Enums in Rust

Enums allow you to define a type that can be one of several variants. In this example, Direction can be North, South, East, or West. Each variant is a distinct value, and Rust ensures you handle al…

SyntaxData Types
Open snippet →
Rust · Beginner

Implementing Methods with impl

The impl block lets you associate functions and methods with a struct. Methods are similar to functions but always have self as their first parameter. The new function acts as a constructor, return…

SyntaxFunctions
Open snippet →
Rust · Beginner

Tuples and Destructuring

Tuples group multiple values of different types into a single compound type. You can destructure a tuple into individual variables using pattern matching. Each position in the tuple has a specific…

Data TypesSyntax
Open snippet →
Rust · Beginner

Working with Vectors

Vectors are dynamic arrays provided by the standard library. You can create them with Vec::new() and push elements, or use the vec! macro for quick initialization. Access elements safely with get()…

Arrays & ListsData Types
Open snippet →
Rust · Beginner

Defining and Calling Functions in Rust

Functions are reusable blocks of code in Rust. They are defined using the `fn` keyword followed by the function name, parameters in parentheses, and an optional return type. Parameters need type an…

FunctionsSyntax
Open snippet →
Rust · Beginner

If Expressions and Conditional Branching

If expressions in Rust work similarly to other languages but have a key difference: they are expressions that return values. Each branch must evaluate to the same type if used as an expression. The…

Control FlowSyntax
Open snippet →
Rust · Beginner

Understanding Scalar Types in Rust

Rust has several scalar types representing single values. Integers come in signed (i) and unsigned (u) variants with sizes from 8 to 64 bits. Signed integers use two's complement representation. Fl…

Data TypesSyntax
Open snippet →
Rust · Beginner

Understanding String vs &str in Rust

Rust has two main string types: owned String and borrowed string slices (&str). String is heap-allocated and growable, while &str is a reference to string data (either borrowed or stored in the bin…

Data TypesMemory Management
Open snippet →
Rust · Beginner

Using Closures with Iterators

Closures are anonymous functions that capture their environment. Combined with iterators, they enable powerful functional programming patterns. The filter method uses a closure to decide which elem…

FunctionsSyntax
Open snippet →
Rust · Beginner

Importing Modules with the use Statement

The use statement brings items into scope, making code cleaner. You can import single items, or use nested paths with curly braces. The self keyword imports the module itself. Question mark operato…

Best PracticesSyntax
Open snippet →
Rust · Beginner

Working with HashMap Key-Value Storage

HashMap stores key-value pairs with O(1) average lookup time. The entry API is powerful for insertion-or-update patterns. or_insert returns a mutable reference to the value, allowing modification.

Data TypesMemory Management
Open snippet →
Rust · Beginner

Handling Optional Values with Option

Option<T> represents a value that might exist or not, avoiding null references. Some contains a value, None represents absence. The if let syntax provides concise pattern matching, while unwrap_or…

Data TypesError Handling
Open snippet →
Rust · Beginner

Defining Structs and Creating Instances

Structs are custom data types that group related fields together. Here we define a User struct with three fields, then create an instance by specifying each field's value. Field access uses dot not…

Data Types
Open snippet →
Rust · Beginner

Pattern Matching with match

The match keyword allows pattern matching against values. It compares the input against each pattern and executes the code for the first matching branch. The underscore _ is a wildcard that matches…

Control Flow
Open snippet →
Rust · Beginner

Ownership Rules at a Glance

Ownership is Rust's unique memory management system. When you assign s1 to s2, ownership moves. s1 is no longer valid. Borrowing with & allows referencing without transferring ownership.

Memory Management
Open snippet →
Rust · Beginner

Writing Your First Unit Test

The #[test] attribute marks a function as a test. assert_eq! checks that two values are equal. Tests run with cargo test and verify your code works correctly.

Testing
Open snippet →