Tsallaka zuwa abun ciki
Justice Tech School

Ownership and Borrowing

Every value has one owner. Assigning a String to another variable moves it. Borrow with & to read without taking ownership, or &mut to change. You may have many readers or one writer at a time.

Example
let s1 = String::from("hello");
let s2 = s1.clone();
println!("{} {}", s1, s2);
fn length(s: &String) -> usize { s.len() }
println!("{}", length(&s1));
let mut text = String::from("hi");
let r = &mut text;
r.push_str(" there");
println!("{}", text);

Result

hello hello
5
hi there

Exercise

Borrow without moving.

length(s1)

Quiz Test

What happens when you move a String?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.