Namara

Code daily. Without assist.

2026-08-21

borrow.rs

fn push_and_print(v: &mut Vec<i32>) {
    let first = &v[0];
    v.push(42);
    println!("{}", first);
}

This doesn't compile. Fix it while keeping the printed value the original first element.

Answer

first borrows v immutably, but v.push needs a mutable borrow, and first is still alive at the println!. Since i32 is Copy, take the value instead of a reference: let first = v[0]; — then push and print freely.