Taking example snippets from here: the following doesn't compile
fn foobar<F>(mut f: F)
where F: FnMut(i32) -> i32
{
println!("{}", f(f(2)));
// error: cannot borrow `f` as mutable more than once at a time
}
fn main() {
foobar(|x| x * 2);
}
but this does
fn foobar<F>(mut f: F)
where F: FnMut(i32) -> i32
{
let tmp = f(2);
println!("{}", f(tmp));
}
fn main() {
foobar(|x| x * 2);
}
I don't understand why the first snippet is illegal: it's effectively the same as the second one, just written more concisely. More specifically, why must f(f(2))
mutably borrow f
twice? It can simply borrow the inner f
to compute the value of f(2)
, and then borrow the outer f
and apply it to the value.
f(f(2))
isn't very nice and adding one of the values into a variable results in better readability. But again just a personal opinion. – Dodecasyllable