Rather than transferring ownership to a function, you can let the function borrow the variable
fn main() {
let str = String::from("Harkirat");
let len = get_length(&str);
println!("{} {}", str, len);
}
fn get_length(str: &String) -> usize {
let len = str.len();
return len
}
When you pass a variable by reference, the variable is still owned by the first function. It is only borrowed by the get_length function.
fn main() {
let str = String::from("Harkirat");
let ref1 = &str;
let ref2 = &str;
println!("{} {}", ref1, ref2);
}
fn main() {
let mut str = String::from("Harkirat");
let ref1 = &mut str;
let ref2 = &str;
println!("{} {}", ref1, ref2);
}
fn main() {
let mut str = String::from("Harkirat");
let ref1 = &mut str;
ref1.push_str("Singh");
let ref2 = &str;
println!("{}", ref2);
}
Goal: Write a function calculate_length that takes an immutable reference to a String and returns its length. Then call this function from main and print both the original String and its length.
Goal: Write a function append_text that takes a mutable reference to a String and appends some text to it. For example, if the string is "Hello", the function could append ", World!".