Learn Rust and develop in a safer way.
These are the notes taken while I was learning Rust on online course made by ZeroToMastery Academy.
💧What we will learn
- vector
- strings
🔥Good Resources
Playground | Replit
Source Code in Github
⚡Vector
- Hold multiple pieces of data(same type)
- Can add, remove and traverse the entries
- use for…in to iterate
🔸Data Structure
let my_numbers = vec![10, 20, 30, 40];
or
fn main() {
let mut my_nums = Vec::new();
my_nums.push(1);
my_nums.push(2);
my_nums.push(3);
my_nums.pop();
my_nums.len(); // 2
let item_1 = my_nums[1];
}
🔸Example
fn main() {
let my_numbers = vec![10, 20, 30, 40];
for num in &my_numbers {
match num {
30 => println!("thirty"),
_ => println!("{:?}", num),
}
}
println!("number of elements = {:?}", my_numbers.len());
}
/*
10
20
thirty
40
number of elements = 4
*/
⚡strings
- 2 commonly used types of strings
- String ( used mostly )
- &str ( pass to function )
fn print_it(data: &str) {
println!("{:?}", data);
}
fn main() {
print_it("A string slice");
let owned_string = "owned string".to_owned();
let another_string = String::from("another");
print_it(&owned_string);
print_it(&another_string);
}
/*
"A string slice"
"owned string"
"another"
*/
🔸Example #02
struct LineItem {
name: String,
count: i32,
}
fn print_name(name: &str) {
println!("name: {:?}", name);
}
fn main() {
let receipt = vec![
LineItem {
name: "Apple".to_owned(),
count: 1,
},
LineItem {
name: String::from("Citrus"),
count: 3,
},
];
for item in receipt {
print_name(&item.name);
println!("count: {:?}", item.count);
}
}
/*
name: "Apple"
count: 1
name: "Citrus"
count: 3
*/
🔸Example #03
struct Person {
name: String,
fav_color: String,
age: i32,
}
fn print(data: &str) {
println!("{:?}", data);
}
fn main() {
let people = vec![
Person {
name: String::from("George"),
fav_color: String::from("green"),
age: 7,
},
Person {
name: String::from("Anna"),
fav_color: String::from("purple"),
age: 9,
},
Person {
name: String::from("Katie"),
fav_color: String::from("blue"),
age: 14,
},
];
for person in people {
if person.age <= 10 {
print(&person.name);
print(&person.fav_color);
}
}
}
/*
"George"
"green"
"Anna"
"purple"
*/