Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

`-> impl Fn()` fails with closures used as `FnMut` but actually Fn #59022

Open
mtak- opened this Issue Mar 8, 2019 · 1 comment

Comments

Projects
None yet
3 participants
@mtak-
Copy link
Contributor

mtak- commented Mar 8, 2019

It's clear that the closure could implement Fn, but for some reason this code does not compile.

fn constrain<F: FnMut()>(f: F) -> F {
    f
}

pub fn foo() -> impl Fn() { // works if FnMut
    constrain(|| {})
}

Error

error[E0277]: expected a `std::ops::Fn<()>` closure, found `[closure@src/lib.rs:6:15: 6:20]`
 --> src/lib.rs:5:17
  |
5 | pub fn foo() -> impl Fn() { // works if FnMut
  |                 ^^^^^^^^^ expected an `Fn<()>` closure, found `[closure@src/lib.rs:6:15: 6:20]`
  |
  = help: the trait `std::ops::Fn<()>` is not implemented for `[closure@src/lib.rs:6:15: 6:20]`
  = note: wrap the `[closure@src/lib.rs:6:15: 6:20]` in a closure with no arguments: `|| { /* code */ }
  = note: the return type of a function must have a statically known size

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=a97dd1def3526265d57cfa1f8236e38a

This bit someone at our company who's relatively new to rust while trying to return a std::iter::Map<.., impl Fn(..)->..>. The Iterator::map function appears to have the same effect as constrain.

@cuviper

This comment has been minimized.

Copy link
Member

cuviper commented Mar 14, 2019

I can reproduce this without impl Fn, just by constraining it different ways:

fn constrain_mut<F: FnMut()>(f: F) -> F { f }
fn constrain<F: Fn()>(f: F) -> F { f }

fn main() {
    // This is fine:
    constrain_mut(constrain(|| {}));
    
    // This complains that `Fn` is not implemented:
    constrain(constrain_mut(|| {}));
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=73333612c7172c48eb68ca7cbc243c3b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.