Rust Fundamentals · 10 XP Pro
References and borrowing
Passing a String to a function moves it, and the caller can no longer use it.
Often a function only needs to look at a value. For that you lend the value
out with a reference: &value creates one, and a parameter of type &String
accepts one.
A reference is a borrow. The owner keeps the data, and when the borrow ends the owner carries on as if nothing happened.
fn shout_len(s: &String) -> usize {
s.len() * 2
}
fn main() {
let name = String::from("Ferris");
let n = shout_len(&name); // lend `name`
println!("{name} {n}"); // still usable
}
Through a &String you can read the value and call methods like len() and
chars(), but you cannot change it.
Your task
Write two pub functions:
count_vowels(text: &String) -> usizereturns how many of the lettersa e i o u(lowercase only) appear intext.same_length(a: &String, b: &String) -> boolreturnstruewhen both strings have the samelen().
Both must borrow their arguments, so the tests can keep using their strings afterwards.