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
make_greeting(name: String) -> String: return"Hello, NAME!", e.g."Hello, Ana!".repeat_word(word: String, times: u32) -> String: the wordtimestimes, separated by single spaces.repeat_word("na".to_string(), 3)is"na na na", and0times gives"". Hint: build with a loop andformat!("{out} {word}"), taking care with the first word.longer_of(a: String, b: String) -> String: return whichever has more bytes (len()); on a tie returna.