-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Mutable reference doesn't coerce to a smaller lifetime #79886
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I think this is working as intended, since |
Yeah, working as intended |
Ok. It seems to be when mutable references or UnsafeCell are involved. This fails to compile: use core::cell::UnsafeCell;
struct Scoped<'a>(UnsafeCell<Option<&'a Scoped<'a>>>);
fn scoped<'a: 'b, 'b>(s: &'b Scoped<'a>) -> Scoped<'b> {
Scoped(UnsafeCell::new(Some(s)))
} Here is an example of something that is very bad that could be done if it allowed it: use core::mem::transmute;
struct Scoped<'a>(Option<&'a mut Scoped<'a>>);
unsafe fn scoped<'a: 'b, 'b>(scoped: &'b mut Scoped<'a>) -> Scoped<'b> {
// This is only safe if we promise to not change the
// mutable reference that `scoped` holds.
Scoped(unsafe { transmute(scoped) })
}
// This changes `scoped` to hold a reference to a dropped struct
fn bad(scoped: &mut Scoped<'_>) {
let mut borrowed_scope = Scoped(None);
let mut scoped_s = unsafe { scoped(scoped) }; // This shortens the used lifetime.
scoped_s.0.as_mut().unwrap().0 = Some(&mut borrowed_scope);
} Should the error possibly be improved to explain that mutable references cannot be coerced to a smaller lifetime and give an example? |
I tried the code below.
The one that uses immutable references works and coerces to a smaller lifetime, but the one that uses mutable references doesn't.
(playground)
Output:
Meta
rustc --version --verbose
:(reposted from #79879 (comment))
The text was updated successfully, but these errors were encountered: