krish
March 17, 2020, 2:04pm
1
The following code works.
fn by_ref(&x: &i32) -> i32{
x + 1
}
fn main() {
let i = 10;
let res1 = by_ref(&i);
let res2 = by_ref(&41);
println!("{} {}", res1,res2);
}
Above, in the function by_ref
, x
has been destructured from &x
in the function parameter.
If I try to do the same thing with a mutable reference it doesn't work. The following code does not work.
fn modifies(&x: &mut f64) {
x = 1.0;
}
fn main() {
let mut res = 0.0;
modifies(&mut res);
println!("res is {}", res);
}
Can someone please explain why? Thanks.
jonh
March 17, 2020, 2:15pm
2
& T
and &mut T
are different types; destructing must match the type.
Also need to make the variable x
be mut to assign to it.
&mut mut x: &mut f64
What you expect out is a different question.
It's right there in the error message: you're trying to destructure a &mut T
as a &T
.
fn modifies(&mut x: &mut f64) {
works.
krish
March 17, 2020, 2:57pm
5
Thanks for the response.
I am afraid fn modifies(&mut x: &mut f64)
doesn't compile. I had tried this out before posting the question.
The previous answer by jonh does compile with warnings. The output is wrong, however. What works is
fn modifies(x: &mut f64) {
*x = 1.0;
}
krish
March 17, 2020, 3:00pm
6
Thanks for the response.
Your answer compiles with warnings. The output is wrong, however. What works is
fn modifies(x: &mut f64) {
*x = 1.0;
}
which was something I knew. Somehow the solution with the destructured parameter seemed prettier.
Could you share the variant which gives wrong output? Maybe there is some misunderstanding.
krish
March 17, 2020, 3:04pm
8
The solution as suggested by jonh compiles with warnings but gives the wrong output( in the rust playground):
fn modifies(&mut mut x: &mut f64) {
x = 1.0;
}
fn main() {
let mut res = 0.0;
modifies(&mut res);
println!("res is {}", res);
}
Destructuring moves out of the target, which requires the Copy
trait to be implemented in this case, since you can't move out of a borrow. So &mut x: &mut i32
gets you, essentially let mut x: i32 = *x;
, which is why it doesn't work as expected - you're making a local copy and modifying it.
3 Likes
krish
March 17, 2020, 3:07pm
10
Got most of what you were saying( am a beginner ). I guess that's it. Thanks.
Oops! Turns out that the compiler error was just off the bottom of my screen; I saw the warnings I expected and so didn't notice. Sorry about that!
system
Closed
June 15, 2020, 10:12pm
12
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.