简体   繁体   English

在Rust中结束可变借用的选项有哪些?

[英]What are the options to end a mutable borrow in Rust?

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. 虽然我通过添加块找到了解决方案,但我很好奇是否有其他方法可以结束可变借用,因此下一个语句可以在之后访问绑定。

Here's what I did so far: 这是我到目前为止所做的:

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]);

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. 我在CanvasRenderer对象的绑定周围包裹了一个块,并且在改变了画布并且范围结束之后, CanvasRenderer死了,我的可变借用canvas可以被读取或者其他任何东西。

This works - but now I'd like to see other solutions! 这有效 - 但现在我想看到其他解决方案!

I heard about drop(stuff) but it did not work as I thought it should. 我听说过drop(stuff)但它没有按照我认为的那样工作。

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. 在Rust 2018之前(在Rust 1.31中可用),所有借词都是词汇,也就是说,它们总是对应于某些词汇范围。 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() 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". drop()不会有两个原因:首先,因为它需要在Rust 2018之前不支持的非词法范围,其次,它不能成为管理借用的通用工具:例如,它不会能够结束不可变借用只是因为不可变引用是Copy而不能被“删除”。

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM