Last time I used a house key to explain a moved value. Once you hand over your only key, you cannot use it yourself. The natural next question is whether you can let someone use a thing without giving it away. In Rust you can, and it is called borrowing.
Think of a shopping list on the fridge. Your friend puts a finger on the first item and goes to find it. While the finger is still there, you take the list down and copy it onto a bigger sheet because you ran out of space. Your friend is now pointing at a place where the list no longer is.
Here is the same thing in Rust.
fn main() { let mut list = vec![String::from("rice"), String::from("dal")]; let first = &list[0]; list.push(String::from("salt")); println!("{first}"); } The compiler stops with error E0502, cannot borrow list as mutable because it is also borrowed as immutable.
The line let first = &list[0]; does not copy the word rice. It only points at it. Then push wants to change the list, and if there is no room left, the vector moves all its items to a new place in memory. The reference would be left pointing at the old place. Rust cannot allow that, so it refuses before the program ever runs.
The fix is to finish reading before you start changing.
fn main() { let mut list = vec![String::from("rice"), String::from("dal")]; let first = &list[0]; println!("{first}"); list.push(String::from("salt")); } This works because the borrow ends at the last place first is used. After that line nobody is pointing at the list, so changing it is safe.
If you really need to keep the item after changing the list, take your own copy with let first = list[0].clone(); and the list is free again.
The rule to remember is that many can read at the same time, or one can change, but not both at once.
You can paste the broken version into
https://borrowfix-smoky.vercel.app and see the real compiler error for yourself.
