Closed
Description
I tried to compile this code:
use std::mem;
use std::ops::{Index, IndexMut};
pub struct FieldMap;
pub fn insert(this: &mut FieldMap, field: &Field<'_>, value: ()) -> () {
this[field] = value;
}
pub struct Field<'a> {
x: &'a (),
}
impl<'a> Index<&'a Field<'a>> for FieldMap {
type Output = ();
fn index(&self, _: &'a Field<'a>) -> &() {
unimplemented!()
}
}
impl<'a> IndexMut<&'a Field<'a>> for FieldMap {
fn index_mut(&mut self, _: &'a Field<'a>) -> &mut () {
unimplemented!()
}
}
I expected the code to compile
Instead, it failed to compile with this lifetime error:
error[E0623]: lifetime mismatch
--> src/lib.rs:7:5
|
6 | pub fn insert(this: &mut FieldMap, field: &Field<'_>, value: ()) -> () {
| ----------
| |
| these two types are declared with different lifetimes...
7 | this[field] = value;
| ^^^^^^^^^^^ ...but data from `field` flows into `field` here
Workarounds
If I change the function in these ways it compiles.
pub fn insert<'a,'b,'c>(this: &'a mut FieldMap, field: &'b Field<'c>, value: ()) -> () {
this[field as &'b Field<'b>] = value;
}
pub fn insert<'a,'b,'c>(this: &'a mut FieldMap, field: &'b Field<'c>, value: ()) -> () {
*this.index_mut(field) = value;
}
Meta
This compiles successfully on Stable Rust 1.45.0 back to 1.26.0 (when '_
lifetimes were stabilized)
This fails to compile on these versions(haven't tried previous ones in the same channels):
This issue has been assigned to @nbdd0121 via this comment.