Rust Fundamentals · 15 XP Pro
Ownership and functions
Passing a value to a function works like assignment: a String argument is
moved into the function, and the caller can no longer use it.
fn consume(s: String) {
println!("{s}");
} // s is dropped here, the text is freed
let word = String::from("bye");
consume(word);
// word is gone now
A function can also hand ownership back by returning the value. Put mut in front
of a parameter name if the function needs to change what it received; the caller's
variable is gone, so nobody can observe the change.
fn add_dot(mut s: String) -> String {
s.push('.');
s // ownership goes back to the caller
}
let sentence = add_dot(String::from("Hello"));
Notice how awkward it gets if you only want to look at a value: you would have to return it just to give it back. The next chapter solves this with references.
Your task
The starter already contains exclaim, which takes a String, appends "!" and
returns it. Add two more functions that build on it:
exclaim_twice(text: String) -> String:"hi"becomes"hi!!". Pass the result of one call straight into the other.shout_and_length(text: String) -> (String, usize): return the upper-cased text (text.to_uppercase()) together with the length of the original text. Read the length first, before the text is consumed.