Jose Quesada
Jose Quesada

Reputation: 477

Are Fn() + 'static and FnMut() + 'static equivalent?

I have what I think to be a simple question, but not much luck finding an answer for it.

Background

I understand the difference between Fn and FnMut in Rust, but I see quite often the need to accept closures that require a 'static lifetime bound.

The Question

Is an Fn() + 'static equivalent to FnMut() + 'static?

My Opinion

In my opinion, I seem to believe they are, because an Fn allows for capturing immutable references to its environment, whereas FnMut, mutable references, however, due to the 'static lifetime bound, the only references they can have, are owned ones, and therefore will almost always have move semantics associated with the closure. Since only owned values, or special &'static references can have 'static lifetime, it seems to me pointless to want to have or need an FnMut() in this case, since there is no mutable reference one might be able to get to the closures environment.

Am I wrong with this conclusion? My guess is yes, otherwise there would probably be a Clippy lint for this.

Upvotes: 1

Views: 513

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601739

Any closure type can capture any kind of data. The difference is how the closure can access the captured data while it is executed. An Fn closure receives a shared reference to its captured data. An FnMut closure receives a mutable reference to its captured data, so it can mutate it. And finally, an FnOnce closure receives ownership of the captrued data, which is why you can call it only once.

The 'static trait bound means that the captured data has static lifetime. This is completely orthogonal to the question what a closure can do with its captured data while it is called.

Upvotes: 4

Related Questions