rust - Rust 赋值和使用借用同时
问题描述
让我感到困惑的是 line 的错误与 lineA
有什么关系C
,因为它们基本上出现在不同的分支中?
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}
pub fn foo(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut p1 = head.as_mut()?;
if let Some(p2) = p1.next.as_mut() {
if true {
p1.next = None; // A: Error here if C is not commented out
} else {
// p1.next = None; // B
p1 = p2; // C: No error on this line
}
}
head
更糟糕的是,错误代码为 E0506,表明尝试分配借用值 ( p1.next
)。为什么我现在不能分配这个借来的值(我相信它是可变借来的),但我可以通过删除 line 来做到这一点C
?
error[E0506]: cannot assign to `p1.next` because it is borrowed
--> src/remove_dup.rs:11:13
|
9 | if let Some(p2) = p1.next.as_mut() {
| ------- borrow of `p1.next` occurs here
10 | if true {
11 | p1.next = None; // A: Error happnens here if C is not commented out
| ^^^^^^^
| |
| assignment to borrowed `p1.next` occurs here
| borrow later used here
解决方案
推荐阅读
- testing - 具有数据属性的选择器
- python - 使用beautifulsoup 直接抓取HTML 表格?
- javascript - Chrome 调试控制台窗口上的“http://localhost:5005/socket.io/?&transport=polling&t=" 错误
- copy - XCOPY 命令将文件复制到 SAN 存储
- angular - NgRx 测试 - NullInjectorError: No provider for Service
- python - 在python中实现解析器的自顶向下递归下降法
- sql - SQL Server 子查询
- go - 这是在工人循环中使用多 wg 的正确方法吗?
- python - python 3.8中异步内部的多处理失败(无法腌制本地对象)
- java - 如何在参数函数中设置任何类型的列表?