Pybites Logo Rust Platform

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

✅ Your task

Implement the following functions in src/main.rs:

  • transfer_ownership: takes ownership of a String, uses it, and returns a new owned value
  • longest_word_length: takes two string references and returns the length of the longer one, without taking ownership
  • to_uppercase: takes a mutable reference to a String and modifies it in place to be uppercase

🔄 Concepts Covered

  • Moving ownership (StringString)
  • 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.


✅ Example tests

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");