Sling Academy
Home/Rust/Preserved keywords in Rust: A cheat sheet

Preserved keywords in Rust: A cheat sheet

Last updated: January 02, 2025

Rust, a systems programming language focused on speed, memory safety, and parallelism, uses a set of reserved keywords. These reserved keywords have specific meanings and purposes within the language and cannot be used as variable names or function identifiers. Understanding these keywords is crucial for writing efficient and semantically correct Rust code. This cheat sheet will guide you through the most common preserved keywords in Rust, explaining their usage and providing examples.

Keyword Categories

In Rust, keywords fall into several categories, making it easier to understand their roles:

  • Control Keywords: Govern the flow of the program.
  • Data Keywords: Define and manipulate custom data types.
  • Primitive Types: Basic types provided by Rust.
  • Pattern Keywords: Used in pattern matching for conditional logic.
  • Miscellaneous Keywords: Other essential keywords that do not fit into the above categories.

Control Keywords

Control keywords are instrumental in executing decisions and loops within a Rust program.

  • if: Used for conditional expressions.
  • else: Provides an alternative in conditional expressions.
  • match: Enables powerful pattern matching.
  • for: Iterates over a collection.
  • while: Executes code as long as a condition is true.
  • loop: Creates an infinite loop.

let number = 6;

if number % 2 == 0 {
    println!("The number is even");
} else {
    println!("The number is odd");
}

for i in 0..5 {
    println!("Number {}", i);
}

Data Keywords

These keywords form the basis for defining and structuring data.

  • struct: Defines a custom data type. Comparable to classes in other languages.
  • enum: Defines an enumeration, a type that can be one of multiple variants.
  • fn: Declares a function.
  • let: Binds a value to a variable.

struct Point {
    x: i32,
    y: i32,
}

fn create_point(x: i32, y: i32) -> Point {
    Point { x, y }
}
let origin = create_point(0, 0);

Primitive Types

Rust's primitive data types are the building blocks for handling common data.

  • i32, u32: Signed and unsigned 32-bit integers respectively.
  • f64: A double-precision floating point.
  • bool: Represents a boolean value.
  • char: A character type representing a Unicode scalar value.

let is_true: bool = true;
let num: i32 = 42;
let character: char = 'R';

Pattern Keywords

Used predominantly in pattern matching expressions for more expressive logic.

  • match: Matches a value against a series of patterns and executes code based on the first successful match.
  • ref, ref mut: Used in patterns to take references to fields or elements.

let number = 2;

match number {
    1 => println!("One"),
    2 => println!("Two"),
    _ => println!("Some other number"),
}

Miscellaneous Keywords

These keywords encompass other vital features offered by Rust.

  • mod: Declares a module.
  • const: Defines a constant item or value.
  • static: Defines a constant item with a fixed memory address.

mod my_module {
    pub const PI: f64 = 3.1415;
}

static HELLO_WORLD: &str = "Hello, world!";

Familiarizing yourself with these keywords in Rust language is an integral part of mastering its syntax and functionality. Keeping this cheat sheet handy can help you write more idiomatic and efficient Rust code.

Next Article: When you should NOT use Rust?

Previous Article: Rust macros cheat sheet

Series: The basics of Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior