问题描述
我正在为借阅检查器苦苦挣扎 - 好奇怪.
I'm strugglin' with the borrow checker - wonder o' wonder.
虽然我通过添加块找到了解决方案,但我很好奇是否有其他方法可以结束可变借用,以便下一条语句之后可以访问绑定.
While I found a solution by adding a block, I am curious if there are other ways to end a mutable borrow so the next statement can access a binding afterwards.
这是我目前所做的:
let mut canvas: Canvas = Canvas {
width: 5,
height: 5,
array: vec!['x'; 5*5],
};
{
let mut renderer: CanvasRenderer = CanvasRenderer::new(&mut canvas);
renderer.render_point('x', 3, 3);
}
println!("The Value in the array is: {}", canvas.array[9]);
我在 CanvasRenderer
对象的绑定周围包裹了一个块,在改变画布和范围结束后,CanvasRenderer
消失,我的可变借用 canvas
可供阅读或其他任何内容.
I wrap a block around the binding of a CanvasRenderer
object and after mutating the canvas and the scope ends, the CanvasRenderer
dies and my mutable borrowed canvas
is available to be read or whatever.
这可行 - 但现在我想看看其他解决方案!
This works - but now I'd like to see other solutions!
我听说过 drop(stuff)
但它并没有像我想象的那样工作.
I heard about drop(stuff)
but it did not work as I thought it should.
推荐答案
没有别的办法;使用块是 的方法.在 Rust 2018(在 Rust 1.31 中可用)之前,所有借用都是词法的,也就是说,它们总是对应于某个词法范围.唯一大于单个语句的作用域是块的作用域,因此块是限制借用作用域的唯一工具.
There is no other way; using blocks is the way to do it. Before Rust 2018 (available in Rust 1.31) all borrows are lexical, that is, they always correspond to some lexical scope. The only scope which is larger than a single statement is that of a block, so blocks are your only tool to limit borrow scopes.
drop()
不起作用有两个原因:首先,因为它需要 Rust 2018 之前不支持的非词法作用域,其次,它不能作为通用工具用于管理借用:例如,它不能仅仅因为不可变引用是 Copy
并且不能删除"而结束 不可变 借用.
drop()
would not work for two reasons: first, because it would require non-lexical scope which is not supported before Rust 2018, and second, it cannot be a general-purpose tool for managing borrows: for example, it wouldn't be able to end an immutable borrow simply because immutable references are Copy
and can't be "dropped".
另见:
这篇关于在 Rust 中结束可变借用的选项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!