We are now on the last chapter of Rust required in order to get started on Scrypto! This chapters goes over Strings, Vectors, and Hashmaps. These are different from the other various ways we have learned to store data such as tuples and arrays. Strings, vectors, and hashmaps are stored on the heap and can grow in size. Here are the links and videos you need to learn this content:
Read chapter 8 of the book here
https://doc.rust-lang.org/book/ch08-00-common-collections.html
Watch Let’s Get Rusty cover chapter 8 here
Watch Tom McGurl cover chapter 8 here
The following is the code used throughout chapter 8 plus some of my own additional notation:
Vectors
// Vectors
fn main() {
// Explicitly declairing the type.
let v: Vec<i32> = Vec::new();
// Letting Rust infer the type
let v_inferred = vec![1, 2, 3]; // using vec! macro to start the vec
//printing just the 3rd element using an index
let third: &i32 = &v_inferred[2];
println!("The third element is {}", third);
//using get to print element if it exists, returns option
match v_inferred.get(3) {
Some(third) => println!("The fourth element is {}", third),
None => println!("There is no fourth element."),
}
// Using new and pushing values to vec
let mut v_mutable = Vec::new();
v_mutable.push(5);
v_mutable.push(6);
v_mutable.push(7);
v_mutable.push(8);
{
let scope_v = vec![1, 2, 3, 4, 5];
// do stuff with v
} // <- V goes out of scope and is freed here
loop_over_vector();
vector_of_enums();
}
fn immutable_borrow_and_mutable_borrow_in_same_scope() {
let mut v = vec![1,2,3,4,5];
// Perform an immutable borrow
let mut first = &v[0];
// v.(6);
println!("The first element is: {}", first);
}
fn loop_over_vector() {
// Immutable vector loop
let v = vec![100, 32, 57];
for i in &v {
println!("{}", i);
}
// Mutable vector loop
let mut v2 = vec![100, 32, 57];
for i in &mut v2 {
*i += 50;
println!("{}", i);
}
}
#[derive(Debug)]
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
fn vector_of_enums() {
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("orange")),
SpreadsheetCell::Float(13.37)
];
match &row[1] {
SpreadsheetCell::Int(i) => println!("{}", i),
_ => println!("Not an integer!")
}
for i in &row {
println!("{:?}", i);
}
}
Strings
// Strings
fn main() {
// Mutable string
let mut s = String::new();
let data = "initial contents";
let s = data.to_string();
// The above is equivalent to
let s = "initial contents".to_string();
// Also
let s = String::from("initial contents");
// UTF-8 Encoded
// let hello = String::from("السلام عليكم");
// let hello = String::from("Dobrý den");
// let hello = String::from("Hello");
// let hello = String::from("שָׁלוֹם");
// let hello = String::from("नमस्ते");
// let hello = String::from("こんにちは");
// let hello = String::from("안녕하세요");
// let hello = String::from("你好");
// let hello = String::from("Olá");
// let hello = String::from("Здравствуйте");
// let hello = String::from("Hola");
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
println!("s2 is {}", s2);
let mut s3 = String::from("lu");
s3.push('l');
combine_strings_with_plus();
iterating_over_strings();
}
fn combine_strings_with_plus() {
let s1 = String::from("Hello, ");
let s2 = String::from("Twitch!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{}-{}-{}", s1, s2, s3);
// is equavalent to: let s = s1 + "-" + &s2 + "-" + &s3;
// this doesnt take ownership of s1, s2, or s3 so they can still be used
println!("s is: {}", s);
println!("s1 is {}", s1);
}
// you cannot specifcy a character of a string with index because not every
//character is stored in the same amount of bytes
fn iterating_over_strings() {
for b in "नमस्ते".bytes() {
println!("{}", b);
}
}
Hashmaps
// Hashmaps
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new(); //creating new empty hashmap
scores.insert(String::from("Blue"), 10); //key - Blue, value - 10
scores.insert(String::from("Red"), 50); //key - Red, value - 50
let team_name = String::from("Blue");
let score = scores.get(&team_name);
println!("{}'s score is: {:?}", team_name, score); //returns: Blue's score is: Some(10)
for (key, value) in &scores {
println!("{}'s score is: {}", key, value) //returns: Red's score is: 50
//Blue's score is: 10
}
overwriting_a_value();
only_insert_value_if_key_has_no_value();
update_value_based_on_old_value();
}
fn vector_of_tuples_to_hashmap() {
let teams = vec![String::from("Blue"), String::from("Red")];
let initial_scores = vec![10, 50];
// We can use <_,_> becuase Rust will infer the type as <String, i32>
let mut scores: HashMap<_,_> =
teams.into_iter().zip(initial_scores.into_iter()).collect();
}
fn ownership_and_hashmaps() {
let field_name = String::from("Favorite color");
let field_value = String::from("Blue");
let mut map = HashMap::new();
map.insert(field_name, field_value);
// field_name and field_value are invalid at this point, try using them and
// see what compiler error you get!
// println!("{}", field_name);
}
fn overwriting_a_value() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
// overwrites score of 10 to 25 for blue team
println!("{:?}", scores);
}
fn only_insert_value_if_key_has_no_value() {
let mut scores = HashMap::new();
// Initial value
scores.insert(String::from("Blue"), 10);
scores.entry(String::from("Red")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
println!("{:?}", scores);
// Only adds score of 50 to Red team since blue had a value already
}
// This will split text up by white space, and iterate over the words
// creating a hashmap showing the count of how many times each word
// is used. Each word will be the hashmap key, each count will be
// the hashmap value.
fn update_value_based_on_old_value() {
let text = "hello twitch wonderful twitch";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{:?}", map);
// returns {"twitch": 2, "wonderful": 1, "hello": 1}
}
Chapter 8 ends with 3 challenges in the summary. Everyone should work on these and create their own solutions so we can compare by end of next week!
- Given a list of integers, use a vector and return the median (when sorted, the value in the middle position) and mode (the value that occurs most often; a hash map will be helpful here) of the list.
- Convert strings to pig latin. The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”). Keep in mind the details about UTF-8 encoding!
- Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.
Please support these great projects for helping us out!
Radup.io
Delphibets.com
Ociswap.com
Scryptochaps.com
Cerberrads.com
Radixdltstaking.com
Spikebrosnft.com
NattyRadishes.com
Radixscan.io
Week 8 winners for participating and helping in this class are:
@NellySayon#0505
@erroll gnargnar#2915
@Arc#7276
@RadixAikoNL#2238
@chiggimps#2176
Please send me your wallet addresses if I don’t already have them, and prizes will be sent out soon!