2021年3月5日星期五

Rust: Mutable borrow returns non-mutable borrow

Apologies if this is asked somewhere else before, but I'm not sure how to search for an answer to this one.

I have a piece of simplified code that demonstrates an issue I'm having in a larger piece of software. Basically I have what (to me) appears to be 2 immutable borrows of an item, however Rust appears to think that one of the borrows is mutable.

struct SomeStruct {      val: i32  }    fn bor_mut(bor: &mut SomeStruct, new_val: i32) -> &i32 {      bor.val = new_val;      &bor.val  }    fn bor_nmut(bor: &SomeStruct) -> &i32 {      &bor.val  }    fn main() {      // get two non-mutable borrows,      // but one originates from a mutable      // borrow      let mut s = SomeStruct{val: 1};      let a = bor_mut(&mut s, 2);      let b = bor_nmut(&s);      println!("a = {}, b = {}", a, b);  }  

Compiling this code gives the following error:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable    --> src/main.rs:20:22     |  19 |     let a = bor_mut(&mut s, 2);     |                     ------ mutable borrow occurs here  20 |     let b = bor_nmut(&s);     |                      ^^ immutable borrow occurs here  21 |     println!("a = {}, b = {}", a, b);     |                                - mutable borrow later used here  

which is simply the "mutable borrow with another borrow" error code. However, the only borrow that exists at line 20 is a, which is immutable. I see where Rust is coming from, since the borrow originates from an immutable borrow, but I don't see how that's relevant when the borrow itself is immutable?

The only reason I can think that this is intended is to prevent multi-threaded code from breaking the borrow checker, but I can't seem to think of a scenario in which this helps even there. However, if that's not the case, it does seem like an oversight in the way the borrow checker works.

I'm hoping someone is able to explain to me why the borrow checker works this way? Somehow this is the first time I've encountered this issue.

https://stackoverflow.com/questions/66501707/rust-mutable-borrow-returns-non-mutable-borrow March 06, 2021 at 10:08AM

没有评论:

发表评论