Borrowing and References: Lending Without Losing
Level: intro (score: 1)
In Rust, borrowing allows you to use a value without taking ownership.
This is different from what we saw in the last exercise, where passing a String
into a function moved it.
Instead, borrowing uses references (&T
) so a function can read data without taking ownership.
Why This Matters
In Python, function arguments are passed by reference by default:
def longer_word_length(word1, word2):
return max(len(word1), len(word2))
text1 = "borrow"
text2 = "rust"
longest = longer_word_length(text1, text2)
print(text1, text2) # Both still accessible!
In Rust, if we passed a String
without borrowing, ownership would be moved, and we couldn’t use the original variables again.
But with references (&String
), we can pass values without transferring ownership.
Task
Implement the function: longest_word_length(word1: &String, word2: &String) -> usize
- The function should take two borrowed strings (
&String
). - It should return the length of the longer string.
- If they are the same length, return that length.
Hints
- Use
.len()
to compare the two words - Since we are borrowing, both
word1
andword2
must remain usable after calling the function. - Why return the length instead of the string itself? Because returning a reference would require lifetimes, which we’ll cover later!
Borrowing is one of Rust’s most powerful features—it ensures safety without unnecessary copying or moving data.
You get memory safety without a garbage collector, and your variables stay where they belong. 💡
Happy coding! 🚀