What is the difference between ownership and borrowing

Ownership grants exclusive control and cleanup responsibility for data, while borrowing allows temporary access without transferring ownership.

Ownership means a variable has exclusive control over data and is responsible for cleaning it up, while borrowing allows temporary access without taking ownership. Ownership transfers when you assign a value to a new variable, but borrowing lets you use the data via references without moving it.

fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // Ownership moves to s2; s1 is invalid
    
    let s3 = String::from("world");
    let len = calculate_length(&s3); // Borrowing: s3 remains valid
    println!("{}", s3); // s3 is still usable
}

fn calculate_length(s: &String) -> usize {
    s.len()
}