pub fn ownership_examples() {
println!("\n🔒 Ownership Examples");
println!("{}", "-".repeat(20));
let s1 = String::from("hello");
let s2 = s1; println!("s2: {}", s2);
let s3 = String::from("world");
let s4 = s3.clone();
println!("s3: {}, s4: {}", s3, s4);
let s = String::from("hello");
takes_ownership(s);
let x = 5;
makes_copy(x);
println!("x is still valid: {}", x); }
fn takes_ownership(some_string: String) {
println!("Taking ownership of: {}", some_string);
}
fn makes_copy(some_integer: i32) {
println!("Making copy of: {}", some_integer);
}
pub fn borrowing_examples() {
println!("\n📚 Borrowing Examples");
println!("{}", "-".repeat(20));
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
let mut s = String::from("hello");
change(&mut s);
println!("Changed string: {}", s);
let r1 = &s;
let r2 = &s;
println!("r1: {}, r2: {}", r1, r2);
let r3 = &mut s;
println!("r3: {}", r3);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}
pub fn slice_examples() {
println!("\n🍰 Slice Examples");
println!("{}", "-".repeat(20));
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
let whole = &s[..];
println!("hello: {}, world: {}, whole: {}", hello, world, whole);
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
println!("Array slice: {:?}", slice);
let word = first_word(&s);
println!("First word: {}", word);
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}