Rust 2021 and partial borrows

According to The Plan for the Rust 2021 Edition | Rust Blog, "Starting in Rust 2021, closures will only capture the fields that they use". This seems highly useful. My question is: does this extend to functions too? How about functions that receive an &self or &mut self? Sometimes, you only need to access self.a in some function access_a, and self.b is some other function access_b (and/or a combination of both a and b)

There's no plan to change methods in the near future.

For public methods this limitation is intentional — the API of the function reserves right to use the whole object, and Rust wants to avoid situations when a change in function's implementation can break users of the function (there's already a fragility caused by implicit Send in async fn).

I've seen people floating ideas about removing this behavior for private methods, where there's no public API to break, or adding more type annotations to be able to express borrowing of individual fields. However, I don't think any of this has progressed past just an idea.

4 Likes

Note that the changes refer to the captured environment of closures, not their parameters. functions can't capture any environment, so this change doesn't apply to them.

10 Likes