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.
Open snippet →Read these Beginner Rust snippets line by line — each one comes with a written breakdown of what the code does and why.
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.
Open snippet →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.
Open snippet →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.
Open snippet →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.
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.
Open snippet →Enums (enumerations) allow you to define a type by enumerating its possible variants. Variants can also hold data.
Open snippet →Vectors allow you to store a variable number of values next to each other in memory. Unlike arrays, they can grow or shrink.
Open snippet →Structs allow you to create custom data types by grouping related values together. Each field has a name and a type.
Open snippet →In Rust, when you assign a complex type like a String to another variable, the data is 'moved' to the new owner. The original variable becomes invalid.
Open snippet →The match operator allows you to compare a value against a series of patterns and execute code based on which pattern matches.
Open snippet →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…
Open snippet →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…
Open snippet →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…
Open snippet →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…
Open snippet →Structs are custom data types that let you package related values together. They are similar to classes in other languages but without methods. In this example, we define a User struct with three f…
Open snippet →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…
Open snippet →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…
Open snippet →Rust allows you to label loops with a lifetime specifier like 'outer. This lets you break out of nested loops from the outer loop. The break without a label exits only the innermost loop, while bre…
Open snippet →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…
Open snippet →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()…
Open snippet →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…
Open snippet →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…
Open snippet →Arrays in Rust are fixed-size collections of elements of the same type. They are declared using square brackets with the type and length separated by a semicolon. Access elements using zero-based i…
Open snippet →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…
Open snippet →Rust supports three types of comments. Single-line comments start with `//` and extend to the end of the line. Multi-line comments are enclosed between `/*` and `*/` and can span multiple lines. Do…
Open snippet →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…
Open snippet →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…
Open snippet →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…
Open snippet →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.
Open snippet →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…
Open snippet →