How does borrowing work with iterators

Iterators borrow collections to process items safely without taking ownership, using .iter() for reading, .iter_mut() for writing, or .into_iter() to consume.

Iterators borrow the collection they iterate over, allowing you to process items without taking ownership or mutating the data unless explicitly requested. Use .iter() to borrow immutably, .iter_mut() to borrow mutably, or .into_iter() to take ownership.

let numbers = vec![1, 2, 3];

// Immutable borrow (read-only)
for n in numbers.iter() {
    println!("{}", n);
}

// Mutable borrow (read-write)
for n in numbers.iter_mut() {
    *n += 1;
}

// Consumes the vector (takes ownership)
for n in numbers.into_iter() {
    println!("{}", n);
}