Ownership and Borrowing
Level: intro (score: 1)
🎯 In Python 🐍, strings are immutable and passed by reference under the hood. In Rust 🦀, you explicitly choose between borrowing(&str
) and owning (String
). Returning data can either borrow from an input (or something it outlives), or allocate a new owned value.
In this exercise, you'll implement three small functions, each demonstrating a key Rust concept:
- ✅ Ownership transfer
- ✅ Shared borrowing
- ✅ Mutable borrowing
Implement the following functions in src/main.rs
:
transfer_ownership
: takes ownership of aString
, uses it, and returns a new owned valuelongest_word_length
: takes two string references and returns the length of the longer one, without taking ownershipto_uppercase
: takes a mutable reference to aString
and modifies it in place to be uppercase
- Moving ownership (
String
→String
) - Shared borrowing (
&String
) - Mutable borrowing (
&mut String
)
No lifetimes required. Use this exercise to start building muscle memory for Rust’s ownership model and borrowing rules.
assert_eq!(transfer_ownership(String::from("hello")), String::from("hello world"));
assert_eq!(longest_word_length(&String::from("hello"), &String::from("world!")), 6);
let mut s = String::from("hello");
to_uppercase(&mut s);
assert_eq!(s, "HELLO");