Skip to content

Instantly share code, notes, and snippets.

@chirag64
Last active January 20, 2023 14:06
Show Gist options
  • Save chirag64/1657834b6cb9df5ee1fd034556796b06 to your computer and use it in GitHub Desktop.
Save chirag64/1657834b6cb9df5ee1fd034556796b06 to your computer and use it in GitHub Desktop.
Kind of like a cheat sheet

How to guide for frequent operations in Rust

For loop - vector

for i in my_vec {
    println!("Current item: {}", i);
}
for (index, item) in my_vec.iter().enumerate() {
    println!("Index: {}, Item: {}", index, item);
}

Loop n number of times

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

// Loop in reverse
for i in (0..100).rev() {
    println!("{}", i);
}

Match Statement

let country_code = 44;

let country = match country_code {
    44 => "UK",
    46 => "Sweden",
    7 => "Russia",
    1..=1000 => "unknown",
    _ => "invalid"
};

println!("The country with code {} is {}", country_code, country);
match country_code {
    44 => {
      println!("UK");
    },
    46 => {
      println!("Sweden");
    },
    7 => {
      println!("Russia");
    },
    1..=1000 => {
      println!("unknown");
    },
    _ => {
      println!("invalid");
    }
};

Create & initialize blank vector

let mut my_vec: Vec<i32> = Vec::new();

// Initialize vector of size n filled with zeroes
let mut my_vec = vec![0; 100]; // Creates int vector for size 100 filled with zeroes

Add item in vector

let mut my_vec = Vec::new();
my_vec.push(1); // [1]
my_vec.push(2); // [1,2]
// Insert at 0th position
my_vec.insert(0, 3); // [3,1,2]
// Insert at 1st position
my_vec.insert(1, 4); // [3,4,1,2]

Sub vector OR slice of a vector

let mut my_vec = [1, 2, 3, 4, 5];
println!("{:?}", my_vec[2..4]) // returns [3, 4]

Push vector into vector to create a Vector of vectors

let mut outer_vec = Vec::new();
let mut inner_vec = Vec::new();
outer_vec.push(inner_vec.to_vec());

Count instances of each element in vector and store into HashMap

// Count instances of each element
let mut map = HashMap::new();
for element in &arr {
    let count = map.entry(element).or_insert(0);
    *count += 1;
}

Pass / receive vector as a function parameter

pub fn modify_vec(new_vec: &mut Vec<i32>) {
    new_vec[4] = 5;
}
let mut my_vec = [1,2,3,4,6].to_vec();
let new_vec = &mut my_vec;
modify_vec(new_vec);

Join vector as string

let split_vec = vec!["This", "is", "a", "sentence"];
let s = split_vec.join(" ");

Convert usize to i32

let u: usize = 2;
let i: i32 = u as i32;

String

let s: &'static str = "hello"; //&str

let mut letters: String = String::new();
letters.push('a');
letters.push_str("bcd");

let u:&str = &letters; // Assign String to &str

let double_letters = letters + &letters; // concatenation

Convert string to i32

let my_int = my_string.parse::<i32>().unwrap();
// OR
let my_int: i32 = my_string.parse().unwrap();

Convert i32 to string

let i: i32 = 10;
let s: String = i.to_string();

Split string into vector of chars

let vec: Vec<char> = str.chars().collect();

Split string into vector of strings

let text = "This is a  sentence";
let split = text.split(" ");
let split_vec: Vec<&str> = text.split(" ").collect();

Join vector of chars into string

let str: String = vec.into_iter().collect();

Loop / Iterate through chars in a string

for c in my_str.chars() { 
    // do something with `c`
}

for (i, c) in my_str.chars().enumerate() {
    // do something with character `c` and index `i`
}

Get length / size of string

let len = s.chars().count();

Convert char to ASCII value int

let ascii_value = 'a' as usize;

Initialize HashMap

use std::collections::HashMap;
let mut hm:HashMap<String, i32> = HashMap::new();

Add key, value in HashMap

hm.insert("one".to_string(), 1);

Add key, value in HashMap only if key does not exist

hm.entry("two").or_insert(2);

Check if key exists in HashMap

if hm.contains_key("one") {
    println!("Hashmap contains key");
}

Get value of key in HashMap

hm.get_mut("one").unwrap();

Update value in HashMap

hm.insert("one".to_string(), 2);

Delete key in HashMap

hm.remove("one");

For loop over HashMap

for (key, value) in &hm {
    println!("{}: {}", key, value);
}

Count instances of characters in a string in a HashMap

use std::collections::HashMap;

let text = "hello world wonderful world";
    
let mut map = HashMap::new();

for char in text.chars() {
    let count = map.entry(char).or_insert(0);
    *count += 1;
}

println!("{:?}", map); // {'h': 1, 'w': 3, 'e': 2, 'l': 5, 'o': 4, ' ': 3, 'n': 1, 'r': 3, 'f': 1, 'u': 1, 'd': 3}

Sort HashMap into a tuple

let mut count_vec: Vec<_> = map.iter().collect();

// Sort the hashmap by key in ascending order
count_vec.sort_by(|a, b| a.0.cmp(b.0));

// Sort the hashmap by value in ascending order
count_vec.sort_by(|a, b| a.1.cmp(b.1));

// Sort the hashmap by value in descending order
count_vec.sort_by(|a, b| b.1.cmp(a.1));

Create & initialize string

let s = "Hello world";
let mut str = String::new(); // Uninitialized string

Get character at nth index in string

s.chars().nth(i).unwrap()

Update character at nth index in string

let s = "Hello world".to_string();
let iter = s.chars();
let mut new_s = String::new();

for (i, mut c) in iter.enumerate() {
    if i == 1 { c = 'i'; }
    new_s.push(c);
}

println!("{}", new_s);

Substring

let s = "Hello world".to_string();
println!("{}", &s[6..11]); // returns "world"

Pass / Receive String as function parameter

pub fn my_func(my_str: &str) {
    println!("{}", my_str);
}

pub fn main() {
    my_func("hello world");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment