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

Closed
mtak- opened this issue Mar 8, 2019 · 2 comments
Closed

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

mtak- opened this issue Mar 8, 2019 · 2 comments

Comments

@mtak-
Copy link
Contributor

@mtak- 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
Copy link
Member

@cuviper 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

@cuviper
Copy link
Member

@cuviper cuviper commented Apr 4, 2019

Closing as a dupe of #26085, which has more details.

@cuviper cuviper closed this Apr 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants