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

Chapter 9.2.5: impl FnOnce() works in 1.35 #1266

Merged
merged 1 commit into from
Sep 23, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions src/fn/closures/output_parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ output parameters should also be possible. However, anonymous
closure types are, by definition, unknown, so we have to use
`impl Trait` to return them.

The valid traits for returns are slightly different than before:
The valid traits for returning a closure are:

* `Fn`: normal
* `FnMut`: normal
* `FnOnce`: There are some unusual things at play here, so the [`FnBox`][fnbox]
type is currently needed, and is unstable. This is expected to change in
the future.
* `Fn`
* `FnMut`
* `FnOnce`

Beyond this, the `move` keyword must be used, which signals that all captures
occur by value. This is required because any captures by reference would be
Expand All @@ -31,12 +29,20 @@ fn create_fnmut() -> impl FnMut() {
move || println!("This is a: {}", text)
}

fn create_fnonce() -> impl FnOnce() {
let text = "FnOnce".to_owned();

move || println!("This is a: {}", text)
}

fn main() {
let fn_plain = create_fn();
let mut fn_mut = create_fnmut();
let fn_once = create_fnonce();

fn_plain();
fn_mut();
fn_once();
}
```

Expand All @@ -46,6 +52,5 @@ fn main() {

[fn]: https://doc.rust-lang.org/std/ops/trait.Fn.html
[fnmut]: https://doc.rust-lang.org/std/ops/trait.FnMut.html
[fnbox]: https://doc.rust-lang.org/std/boxed/trait.FnBox.html
[generics]: ../../generics.md
[impltrait]: ../../trait/impl_trait.md