(rust noob here; I'm trying to understand what can/cannot/should/shouldn't be passed by reference in a higher order function situation)
let a = [1, 2, 3];
This invocation works:
let sum = a.iter().fold(0, |acc: i32, x: &i32| acc + x);
These do not:
let sum = a.iter().fold(0, |acc: i32, x: i32| acc + x);
let sum = a.iter().fold(0, |acc: &i32, x: i32| acc + x);
The error message is
error[E0631]: type mismatch in closure arguments
--> main.rs:8:22
|
8 | let sum = a.iter().fold(0, |acc: &i32, x: i32| acc + x);
| ^^^^ --------------------------- found signature of `for<'r> fn(&'r i32, i32) -> _`
| |
| expected signature of `fn({integer}, &{integer}) -> _`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0631`.
The explanation does not offer anything of interest. It says the arguments of the closure do not match those of the arguments of fold. I however cannot see how it follows from the declaration of fold:
fn fold<B, F>(self, init: B, f: F) -> B
where
F: FnMut(B, Self::Item) -> B
Why is the second argument supposed to be &{integer}, and the first one {integer}?