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) -> usize returns how many of the letters a e i o u (lowercase only) appear in text.
  • same_length(a: &String, b: &String) -> bool returns true when both strings have the same len().

Both must borrow their arguments, so the tests can keep using their strings afterwards.

Next lesson →

Sign in to run your code. It's free.