Pybites Logo Rust Platform

Shared References

Easy +2 pts

Moving ownership everywhere gets tedious. What if you just want to look at a value without taking it?

In Python, everything is passed by reference automatically:

def print_length(items): print(len(items)) # just reads, doesn't modify names = ["Alice", "Bob"] print_length(names) print(names) # still valid

In Rust, you borrow with &:

fn print_length(items: &Vec<String>) { println!("{}", items.len()); } let names = vec!["Alice".to_string(), "Bob".to_string()]; print_length(&names); // lend with & println!("{:?}", names); // still ours

The borrowing rules

Login to see the full exercise.