E0502 rust type_error ai_generated true

error[E0502]: cannot borrow `vec` as mutable because it is also borrowed as immutable --> src/main.rs:10:5 | 8 | let first = &vec[0]; | ------ immutable borrow occurs here 9 | vec.push(1); 10 | println!("{}", first); | ^^^^^^^^^^^^^^^^^^^^^^^ immutable borrow later used here

ID: rust/e0502-borrow-mut-and-immut-in-vec

Also available as: JSON · Markdown · 中文
88%Fix Rate
86%Confidence
1Evidence
2023-11-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
rustc 1.74 active
rustc 1.75 active

Root Cause

Holding an immutable reference to a `Vec` element while trying to mutate the `Vec` (e.g., push), which could invalidate the reference.

generic

中文

持有对 `Vec` 元素的不可变引用,同时尝试修改 `Vec`(例如 push),这可能会使引用失效。

Official Documentation

https://doc.rust-lang.org/stable/error_codes/E0502.html

Workarounds

  1. 90% success Clone the element you need before mutating: `let first = vec[0].clone(); vec.push(1); println!("{}", first);`
    Clone the element you need before mutating: `let first = vec[0].clone(); vec.push(1); println!("{}", first);`
  2. 85% success Use indices instead of references: `let first_index = 0; vec.push(1); println!("{}", vec[first_index]);`
    Use indices instead of references: `let first_index = 0; vec.push(1); println!("{}", vec[first_index]);`

中文步骤

  1. 在修改前克隆你需要的元素:`let first = vec[0].clone(); vec.push(1); println!("{}", first);`
  2. 使用索引代替引用:`let first_index = 0; vec.push(1); println!("{}", vec[first_index]);`

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Leads to undefined behavior; the Vec may reallocate and invalidate the pointer.

  2. 50% fail

    Inefficient and doesn't solve the borrow conflict; still need to manage lifetimes.