-
- Notifications
You must be signed in to change notification settings - Fork 14.2k
Description
For the following contrived code that should be using FnOnce instead of Fn (playground link):
pub fn in_transaction<F>(callback: F) -> Result<(), ()> where F: Fn() -> Result<(), ()>, { let result = callback()?; Ok(result) } struct Foo; fn foo(foos: &mut [&mut Foo]) -> Result<(), ()> { in_transaction(|| { for foo in foos { drop(foo); } Ok(()) })?; Ok(()) }The compiler (1.92 stable) generates the following error and suggestions:
error[E0507]: cannot move out of `foos`, a captured variable in an `Fn` closure --> src/lib.rs:13:20 | 11 | fn foo(foos: &mut [&mut Foo]) -> Result<(), ()> { | ---- --------------- move occurs because `foos` has type `&mut [&mut Foo]`, which does not implement the `Copy` trait | | | captured outer variable 12 | in_transaction(|| { | -- captured by this `Fn` closure 13 | for foo in foos { | ^^^^ | | | `foos` moved due to this implicit call to `.into_iter()` | `foos` is moved here | help: `Fn` and `FnMut` closures require captured values to be able to be consumed multiple times, but `FnOnce` closures may consume them only once --> src/lib.rs:3:8 | 3 | F: Fn() -> Result<(), ()>, | ^^^^^^^^^^^^^^^^^^^^^^ note: `into_iter` takes ownership of the receiver `self`, which moves `foos` --> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:310:18 | 310 | fn into_iter(self) -> Self::IntoIter; | ^^^^ help: consider creating a fresh reborrow of `foos` here | 13 | for foo in &mut *foos { | ++++++ For more information about this error, try `rustc --explain E0507`. error: could not compile `playground` (lib) due to 1 previous error The first part of the diagnostics (correctly identifying !Copy, Fn/FnMut vs FnOnce) is correct and useful, but the second part is somewhat misleading (and I believe the compiler has the necessary information to avoid from suggesting it) as a fresh reborrow wouldn't (directly) resolve the issue (at least, not directly? It would cause further errors because foos wasn't borrowed as mut, then errors because you're using Fn instead of FnMut, but if you patch those and assuming you're able to use FnMut instead of Fn to begin with, it'll work. So I'm not entirely sure whether or not this should be considered a helpful suggestion or not.
@rustbot label +T-compiler +A-diagnostics +D-invalid-suggestion +A-closures