Rust Fundamentals · 20 XP Pro

Capstone: building and returning Strings

Functions that build a new String and return it are the cleanest use of ownership: the value is created inside, moved out through the return, and the caller becomes its owner. Nothing dangles and nothing needs cleanup by hand.

fn banner(title: String) -> String {
    format!("== {title} ==")
}

format! works like println! but returns a new String instead of printing. It only reads its arguments, so title is still usable after the call inside the function.

Other handy tools: String::new() for an empty string, push to add a char, and push_str("literal") to add text.

When a function takes two Strings and returns only one of them, the other is dropped when the function ends. That is fine: you handed it over, so cleaning it up is the function's job.

Your task

  1. make_greeting(name: String) -> String: return "Hello, NAME!", e.g. "Hello, Ana!".
  2. repeat_word(word: String, times: u32) -> String: the word times times, separated by single spaces. repeat_word("na".to_string(), 3) is "na na na", and 0 times gives "". Hint: build with a loop and format!("{out} {word}"), taking care with the first word.
  3. longer_of(a: String, b: String) -> String: return whichever has more bytes (len()); on a tie return a.

Next lesson →

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