Copy semantics is not being applied to closures

I have this simple function:

fn multiplier(num: i32) -> impl Fn(i32) -> i32 {
	|x| x * num
}

but it is refusing to compile because num is being borrowed. If it needs to be compiled I've to 'move' it. But, since num is an integer which implements copy trait, it can just be copied instead of being moved. So, why is it not being copied?

It is being copied, if you use move.

Closures don't know anything about Copy. It's the borrow checker who checks that the moved value are not used anymore and allows to move a copy of Copy value. The only thing the closure can do here is to request the move (which can then be turned into copy) - or don't do it and use a borrow.

4 Likes

you're right. I checked it by slightly modifying the function to this:

fn multiplier(num: i32) -> impl Fn(i32) -> i32 {
	let mul =move |x:i32| x * num;
	println!("{}", num);
	mul
}

It compiled it successfully. Thanks for the answer