Rust Cheatsheet

kuniga.me > Docs > Rust Cheatsheet

Rust Cheatsheet

Index

  1. Basic types
    1. Type names
    2. Arrays
      1. Initialize
      2. Iterate
    3. Bool
    4. Optional
    5. String
      1. Types
      2. Concatenation
    6. Struct
      1. Destructuring
      2. Methods
    7. Tuple
    8. Functions
    9. Closure
      1. Multi-line
    10. Conditional
    11. Loops
    12. Bit operations
  2. Data structures
    1. Vec - dynamic sized list
      1. Initialize
      2. Inserting
      3. Iterating
      4. Mapping
      5. Filtering
      6. Length
    2. HashMap
    3. String - variable length characters
  3. Object Oriented

Basic types

Type names

Arrays

Arrays are of fixed size. For variable size, see Vec.

Initialize

// Initialize array
let arr: [i32; 3] = [1, 2, 3];
let arr: [i32; 10] = [0; 10];

Iterate

let arr: [i32; 3] = [1, 2, 3];
for x in &arr {
    print!("{} ", x);
}

Bool

Optional

// Handle option:
match my_option {
    Some(value) => value,
    None => 1, // handle null value
}

// Create Some
Some(1)

// Throw if None
my_option.unwrap()

// Test if some
my_option.is_some()

// Test if none
my_option.is_none()

String

Types

Concatenation

let concatenated = format!("{}{}", a, b);

or

let s = "hello".to_owned();
let t = " world".to_owned();
s. push_str(&t);

Struct

keywords: record / object / shape

struct Tree {
    guess: Vec<i32>,
    children: Vec<Tree>,
}

Destructuring

let foo = Foo { x: (1, 2), y: 3 };
let Foo { x: (a, b), y } = foo;

Methods

struct Rectangle {
    length: u32,
    width: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.length * self.width
    }
}

Tuple

let tup: (i32, String) = (64, "hello")
// Can be accessed in the . notation
tup.0 // 64
tup.1 // "hello"

Functions

fn myFun(arg1: i32, arg2: i32) -> i32 {
}

Rust doesn’t support default arguments

Closure

keywords: lambda

    let plus_one = |x: i32| x + 1;

Multi-line

let multi_line = |x: i32| {
    let mut result: i32 = x;
    result += 1;
    result
}

Conditional

if n < 0 {
    print!("{} is negative", n);
} else if n > 0 {
    print!("{} is positive", n);
} else {
    print!("{} is zero", n);
}

Loops

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

See also “Iterating” on different data structures.

Bit operations

! is the Rust version of ~

Data structures

Vec - dynamic sized list

Initialize

let mut vec = Vec::new();

Inserting

vec.push(1);

Iterating

for item in vec.iter() {
    ...
}

Mapping

let u = vec![1, 2, 3];
let v: Vec<_> = u.iter().map(f).collect();

Filtering

let u = vec![1, 2, 3];
let v: Vec<_> = u.iter().filter(f).collect();

In-place

let mut u = vec![1, 2, 3];
u.retain(f);

Length

vec.len()

HashMap

Reference: HashMap

use std::collections::HashMap;

// Type definition
HashMap<String, String>;

// Create New
my_map = HashMap::new()

// Insert
my_map.insert(
    "key_a".to_string(),
    "value_a".to_string(),
);

// Access
match my_map.get("key_a") {
    Some(value) => println!("value={}", value),
    None => println!("not found")
}

// All values
for value in my_map.values() {
}

// All keys
for key in my_map.keys() {
}

String - variable length characters

// Empty string
let mut my_str: String = "".to_owned();

// Other form
let mut my_str = String::from("Hello");

// Length
my_str.len();

// Iterate over its characters
for c in my_str.chars() {
    // do something with c
}

Object Oriented

pub structure MyClass {
    my_field: bool,
}

impl MyClass {
    // Constructor-like
    pub fn new() -> MyClass {
        return MyClass {
        my_field: true,
        }
    }

    // Read Method
    pub fn set(&self, value: bool) {
        self.my_field = value;
    }

    // Write Method
    pub fn set(&mut self, value: bool) {
        self.my_field = value;
    }
}