E0502 rust type_error ai_generated true

错误[E0502]:不能将 `vec` 作为可变借用,因为它也被作为不可变借用 --> src/main.rs:10:5 | 8 | let first = &vec[0]; | ------ 这里发生了不可变借用 9 | vec.push(1); 10 | println!("{}", first); | ^^^^^^^^^^^^^^^^^^^^^^^ 不可变借用稍后在这里使用

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

其他格式: JSON · Markdown 中文 · English
88%修复率
86%置信度
1证据数
2023-11-01首次发现

版本兼容性

版本状态引入弃用备注
rustc 1.74 active
rustc 1.75 active

根因分析

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

English

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

generic

官方文档

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 50% 失败

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