COLLECTIONS
TUPLES
- Tuples are unnamed groups of data.
- They are heterogenous collection.
- The below example shows a basic tuple and ways to unpack it.
let fruits: (&str, &str) = ("Apple", "Grapes"); // Can be unpacked like below let fruit1: &str = fruits.0; let fruit2: &str = fruits.1; // Or can be unpacked like below let (fruit1: &str, fruit2: &str) = fruits;
- You can unpack a single value of tuple by given below format
let fruits: (&str, &str) = ("Apple", "Grapes"); let (_, fruit2: &str) = fruits;
VECTOR
- They are two-dimensional array of data.
- They are called list in python and array in many other languages like javascript, java etc..
- You can define a vector of fixed size by given format:
let fruits: [&str; 4] = ["Apple", "Mango", "Grapes", "Pineapple"];
- You can loop (iter) through the vector using iter
for fruit::&&str in fruits.iter(){ println!("Fruit {}", fruit); }
- You can get reference a value of vector in the given format
let apple: &&str = &fruits[0];
- Length of a vector can be found using below method:
let fruit_len: usize = values.len();
- You can map through a vector like below:
let values: [i32; 4] = [1, 2, 3, 4]; let doubles: impl Iterator<Item = i32> = values.iter().map(|x: &i32| x*3);
- You can define a vector of non-fixed size like below using vec! :
let values: Vec<i32> = vec![1, 2, 3, 4];
- You can define a vector of non-fixed size like below using vec! :
let mut values: Vec<i32> = vec![1, 2, 3, 4];
- You can push values into like below
values.push(5);
- You can pop a value like below:
let five: Option<i32> = values.pop();
- You can clear values from a vector like below:
values.clear();
- You can extend an Vector like below:
values.extend_from_slice(&[5, 6, 7, 8]);
- You can move values from one ector to another like below:
let mut values1: Vec<i32> = vec![1, 2, 3, 4]; let mut values2: Vec<i32> = vec![5, 6, 7, 8]; values2.append(&mut values1);
- You can check if a vector contains a value or not like below:
let mut values1: Vec<i32> = vec![1, 2, 3, 4]; if values1.contains(&1){ println!("Vector contains 1"); }
- You can check if a vector is empty like below:
let mut values1: Vec<i32> = vec![1, 2, 3, 4]; values1.clear(); if values1.is_empty(){ println!("Vector is empty"); }
HASHMAP
- They are key value collection.
- They are called dictionary in other languages.
- In order to use hashmap, you will need to import it like below:
use std::collections::HashMap;
- You can define a simple hashmap like below:
let values: HashMap<&str, &str> = HashMap::new();
- You can insert values into a hashmap like below:
values.insert(k: "foo", v:"bar");
- You can check if a hashmap contains a key like below:
if values.contain_key("foo"){ println!("HashMap doesn't contain foo"); }
- You can remove a key values pair for hashmap like below:
values.remove("foo");
- You can read a value from hashmap like below:
let bar: &str = values["foo"];
- The above method of reading values only works if the key exists in the hashmap else it throws an error.
- The safe method to read it is like below:
match values.get("foo"){ Some(values: &&str) => println!("{}", values), None => println!("Not found"), }
- You can iterate over hashmap like below:
for (&k: &str, &v: &str) in &values{ println!("{}: {}",k, v); }
- You can get a specific entry(key, value) from hashmap like below:
let entry: Entry<&str, &str> = values.entry(key: "foo");
- You can match like below:
match entry { std::collections::hash_map::Entry::Occupied(value) => println!("{}",value.get()), _ => println("Not found") }
- You add key value pair in to hashmap if key not present like below:
values.entry(key: "name").or_insert(default: "Sanu");
- You add structure into hashmap like below:
struct Person{ name: String, age: u8 } fn main(){ let mut values: HashMap<Person, &str> = HashMap::new(); }
- Hashmap uses hashing algorithm to convert the values needed to be stored as a unique numeric representation, so if you create two Person with same age and name, ie, a Person John with age 30 and another Person with name John and age 40. then the second one will replace the first one if we calculate the hash value using the name only then they are the same.
- If we need to rust to calculate the hash value you need to add traits, Hash, Eq, PartialEq, Debug like below:
#[derive(Debug, Eq, Hash, PartialEq)]
ITERATOR
- Iterator allows you to iterate over a collection of data like vector, hashmap etc..
- Iterators in Rust is lazy, ie you acutally need to consume it to do something.
- Iterator in rust uses a trait called iterator.
- Basic iterator example is given below:
let values: Vec<i32> = vec![1, 2, 3]; for value: &i32 in values.iter(){ println!("{}", value); }
- Iterator cannot be double consumed, i.e, you cannot reuse it once it is used like below, as it will throw an error.
let values: Vec<i32> = vec![1, 2, 3]; let iter: Iter<i32> = values.iter(); let sum1: i32 = iter.sum(); let sum3: i32 = iter.sum();
- Once it is consumed it has gone from the begining to the end, i.e, its pointer is at the end.
- Thus you will need to define another iterator if you need another one.
let values: Vec<i32> = vec![1, 2, 3]; let iter: Iter<i32> = values.iter(); let sum1: i32 = iter.sum(); let iter2: Iter<i32> = values.iter(); let sum3: i32 = iter2.sum();
- The above block of code is valid as it creates another iterator instead of using the same iterator.
- You can add map on iterator like below:
let values: Vec<i32> = vec![1, 2, 3]; let multiplied_by_2: Iter<i32> = values.iter().map(|x: &i32| x*3).collect();
- When you are using iteration, you are working with the reference inside that collection.
- Incase you need to get owned values i.e, the values are moved from the iterator out into the iteration, you can use into_iter()
for fruit: &str in fruits.into_iter(){ println!("Fruit {}", fruit); }
- You can add filter into iterator like below
for fruit: &str in fruits.into_iter(|fruit| fruit.len() == 3){ println!("Fruit {}", fruit); }
Comments
Post a Comment