# 错误[E0502]：不能将 `vec` 作为可变借用，因为它也被作为不可变借用

  --> src/main.rs:10:5
   |
 8 |     let first = &vec[0];
   |                  ------ 这里发生了不可变借用
 9 |     vec.push(1);
10 |     println!("{}", first);
   |     ^^^^^^^^^^^^^^^^^^^^^^^ 不可变借用稍后在这里使用

- **ID:** `rust/e0502-borrow-mut-and-immut-in-vec`
- **领域:** rust
- **类别:** type_error
- **错误码:** `E0502`
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| rustc 1.74 | active | — | — |
| rustc 1.75 | active | — | — |

## 解决方案

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

## 无效尝试

- **** — Leads to undefined behavior; the Vec may reallocate and invalidate the pointer. (90% 失败率)
- **** — Inefficient and doesn't solve the borrow conflict; still need to manage lifetimes. (50% 失败率)
