A Handy Rust Cheat Sheet for Beginners

Nyakio MainaNyakio Maina
2 min read

1. Variables and Data Types

  • Declare a variable (immutable by default):

      let variable_name = value;
    
  • Declare a mutable variable:

      let mut variable_name = value;
    
  • Specify a data type:

      let variable_name: data_type = value;
    
  • Common data types:

    • Integer: i32, u32, i64, u64

    • Floating-point: f32, f64

    • Boolean: bool

    • Character: char

    • String: String

    • Array: [T; N] (T: type, N: length)

    • Tuple: (T1, T2, T3) (T1, T2, T3: types)

2. Control Flow

  • if statement:

      if condition {
          // code
      } else if other_condition {
          // code
      } else {
          // code
      }
    
  • loop statement (infinite loop):

      loop {
          // code
      }
    
  • while loop:

      while condition {
          // code
      }
    
  • for loop:

      for variable in iterable {
          // code
      }
    

3. Functions

  • Define a function:

      fn function_name(parameter: data_type) -> return_type {
          // code
      }
    
  • Call a function:

      function_name(argument);
    

4. Enums and Pattern Matching

  • Define an enum:

      enum EnumName {
          Variant1,
          Variant2,
          Variant3(data_type),
      }
    
  • match statement:

      match value {
          EnumName::Variant1 => {
              // code
          },
          EnumName::Variant2 => {
              // code
          },
          EnumName::Variant3(variable) => {
              // code
          },
          _ => {
              // code
          },
      }
    

5. Error Handling

  • Result enum for error handling:

      enum Result<T, E> {
          Ok(T),
          Err(E),
      }
    
  • match statement with Result:

      match result {
          Ok(value) => {
              // code
          },
          Err(error) => {
              // code
          },
      }
    
  • ? operator for propagating errors:

      let result = function_returning_result()?;
    

6. Collections

  • Create a vector:

      let mut vector = Vec::new();
      // or
      let vector = vec![value1, value2, value3];
    
  • Create a hash map:

      use std::collections::HashMap;
      let mut hash_map = HashMap::new();
    
  • Create a hash set:

      use std::collections::HashSet;
      let mut hash_set = HashSet::new();
    

Detailed CheatSheet:
https://cheats.rs/

5
Subscribe to my newsletter

Read articles from Nyakio Maina directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nyakio Maina
Nyakio Maina

Software QA Engineer with knowledge and experience coding in javascript and typescript and learning Rust programming language