Pybites Logo Rust Platform

Mutable References

Medium +3 pts

Shared references (&T) are read-only. To modify borrowed data, you need a mutable reference (&mut T):

fn add_greeting(text: &mut String) {
    text.push_str(", hello!");
}

let mut message = String::from("World");
add_greeting(&mut message);
assert_eq!(message, "World, hello!");

Python comparison

In Python, you can modify objects passed to functions because everything is a reference:

def add_item(items, item):
    items.append(item)

my_list = [1, 2]
add_item(my_list, 3)
print(my_list)  # [1, 2, 3]

This is convenient but dangerous — any function might modify your data unexpectedly. Rust makes mutation explicit with &mut.

The exclusivity rule

Rust enforces a critical safety rule: you can have many shared references OR one mutable reference, …

Login to see the full exercise.