cg909
July 1, 2024, 10:06am
3
This sounds a lot like "downgradable" or "downgrading" borrows that were discussed before:
Some months ago I've read the following comment by steffahn and I think a generalized &mut T could be viable.
So here's my very first Pre-RFC based on that idea:
Summary
Generalize &mut with a second, optional lifetime to allow opt-in downgradeable borrows.
Motivation
Currently coercing or reborrowing a &mut as an immutable reference always extends the unique borrow to the lifetime of the resulting reference.
When interior mutability is involved, this behavior is neccessary for correctness …
struct Foo{
name: String,
score: u32
}
impl Foo{
fn new(id: String, score: u32) -> Foo{
Foo { name: id, score: score }
}
fn add_score(&mut self) -> &u32 {
self.score += 1;
&self.score
}
fn get_name(&self) -> &String {
&self.name
}
}
fn main() {
let mut foo = Foo::new("foo".into(), 0);
let score = foo.add_score();
let name = foo.get_name();
println!("{}: {}", name, score);
}
error[E0502]: cannot borrow `foo` as …
The main problem is that it must stay impossible to get a shared borrow from an unique/mutable borrow when interior mutability is involved. So your BorrowHybrid::immut()
may not be called when Borrowed
has interior mutability.
11 Likes