Ownership and Borrowing
Level: intro (score: 1)
🚀 These intro exercises are prep for our
Rust Intro Cohort Program.
🎯 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");
// --- Ownership: move in ---
pub fn transfer_ownership(name: String) -> String {
// TODO: Return a greeting like "Welcome, <name>!"
todo!()
}
// --- Borrowing: shared ---
pub fn longest_word_length(word1: &String, word2: &String) -> usize {
// TODO: Return the length of the longer word
todo!()
}
// --- Borrowing: mutable ---
pub fn to_uppercase(text: &mut String) {
// TODO: Convert the input string to uppercase in-place
todo!()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_transfer_ownership() {
let username = String::from("Alice");
let result = transfer_ownership(username);
assert_eq!(result, "Welcome, Alice!");
}
#[test]
fn test_longest_word_length() {
let text1 = String::from("borrow");
let text2 = String::from("rust");
let result = longest_word_length(&text1, &text2);
assert_eq!(result, 6);
}
#[test]
fn test_to_uppercase() {
let mut word = String::from("rust");
to_uppercase(&mut word);
assert_eq!(word, "RUST");
}
}