I cannot figure out, why the following code doesn't compile (Rust Playground):
pub fn main(old: &mut Option<i32>) {
let neew = MaybeChanged::new(old, Some(42));
//let sub = MaybeChanged::new(&old, &neew.data);
let sub = MaybeChanged::new(&old.as_ref(), neew.data.as_ref());
*old = None;
drop(sub)
}
pub struct MaybeChanged<T> {
pub data: T,
pub is_changed: bool,
}
impl<T> MaybeChanged<T> {
fn new<U: PartialEq<T>>(old: &U, new: T) -> Self {
Self {
is_changed: old == &new,
data: new,
}
}
}
error[E0506]: cannot assign to `*old` because it is borrowed
--> src/lib.rs:6:5
|
4 | let sub = MaybeChanged::new(&old.as_ref(), neew.data.as_ref());
| ------------ `*old` is borrowed here
5 |
6 | *old = None;
| ^^^^^^^^^^^ `*old` is assigned to here but it was already borrowed
7 | drop(sub)
| --- borrow later used here
If I use Line 3 instead of Line 4, everything works fine. How can it be, that the lifetime of old
is captured, when the the first param in MaybeChanged::new
has nothing to do with it's output?