I was trying to write something like the following:
fn bar(ret: Option<&mut i32>) {...}
fn foo(ret: Option<&mut i32>) {
bar(ret);
bar(ret); // error: `ret` is moved
}
this link suggests to use ret.as_deref_mut()
, but the fact that I need to declare the option as mut
bugs me.
So I went a little further and found this.
Taking the example from the link:
struct Foo {
value: Vec<i32>,
}
let a: Option<&mut Foo> = ...;
if let Some(&mut ref mut x) = a { // `a` is not moved!
x.value.push(0);
}
if let Some(&mut ref mut x) = a {
x.value.push(0);
}
Now I'm a little confused since it seems that the code effectively mutates a
without taking ownership of it, even though it is not declared mut
!
Isn't it a violation of Rust's principle??
If it is a valid code, is there a way to simplify it without using if let
?
I tried the following but map
takes the ownership of Option
so a
cannot be used again.
let a: Option<&mut Foo> = ...;
a.map(|&mut ref mut x| x.value.push(0));