gpt4 book ai didi

Rust 模式匹配 Option 的引用,一种方式工作,但另一种方式不工作(借用检查器不通过)

转载 作者:行者123 更新时间:2023-12-03 11:25:03 25 4
gpt4 key购买 nike

在 Rust 中,如果结构是这样的

struct Node {
next: Option<Box<Node>>,
}
然后实现一个方法来找到尾部并在其上添加一个新节点可能看起来像这样
fn add1<'a>(mut node: &'a mut Node) {
while let Some(next) = node.next.as_deref_mut() {
node = next;
}
node.next = Some(Box::new(Node { next: None }));
}
然后遇到这样的错误:
error[E0506]: cannot assign to `node.next` because it is borrowed
--> src/lib.rs:16:5
|
12 | fn add1<'a>(mut node: &'a mut Node) {
| -- lifetime `'a` defined here
13 | while let Some(next) = node.next.as_deref_mut() {
| ------------------------
| |
| borrow of `node.next` occurs here
| argument requires that `node.next` is borrowed for `'a`
...
16 | node.next = Some(Box::new(Node { next: None }));
| ^^^^^^^^^ assignment to borrowed `node.next` occurs here
其他一些变体也不起作用:
fn add1_borken_ergonomics(mut node: &mut Node) {
while let Some(next) = &mut node.next {
node = next;
}
node.next = Some(Box::new(Node { next: None }));
}

fn add1_borken_explicit<'a>(mut node: &'a mut Node) {
while let Some(ref mut next) = *&mut node.next {
node = next;
}
node.next = Some(Box::new(Node { next: None }));
}
这给出了类似的错误
error[E0506]: cannot assign to `node.next` because it is borrowed
--> src/lib.rs:30:5
|
26 | fn add1_borken_explicit(mut node: &mut Node) {
| - let's call the lifetime of this reference `'1`
27 | while let Some(ref mut next) = *&mut node.next {
| ------------ -------------- borrow of `node.next` occurs here
| |
| assignment requires that `node.next` is borrowed for `'1`
...
30 | node.next = Some(Box::new(Node { next: None }));
| ^^^^^^^^^ assignment to borrowed `node.next` occurs here
所以问题是,为什么写这样的文章会 工作
fn add1_working<'a>(mut node: &'a mut Node) {
while let Some(ref mut next) = node.next {
node = next;
}
node.next = Some(Box::new(Node { next: None }));
}
上面的代码应该都是一样的,但编译器对它们的处理方式不同吗?
Rust playground for the example code above .同样的问题可以在 another simpler code example 上看到以及(从问题页面,见下文。)
在四处询问后,我发现了一个与此相关的问题 https://github.com/rust-lang/rust/issues/67957 ,但似乎没有提到是不是一些编译器的bug可以稍后修复,还是因为我们需要对语言的某些方面有更好的理解?

最佳答案

这是一个已知的 bug .
我收到了 explanation来自 Rust 论坛:

There's another bug report related to this, similar to the one linked in thatStackOverflow thread but with a bit more discussion: if/while Some(n) = &mut foo sugar will leak a temporary mutable borrow to current scope in particular situation · Issue #62013 · rust-lang/rust · GitHub

I didn't follow all of the details, but I believe the difference in behavior here is unintentional and will be fixed eventually. When compiling with the next-generation borrow checker Polonius, both functions compile successfully.

关于Rust 模式匹配 Option 的引用,一种方式工作,但另一种方式不工作(借用检查器不通过),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66382519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com