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

Update 19-5 to demonstrate returning a closure using impl Trait #3536

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "functions-example"
version = "0.1.0"
edition = "2021"

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn returns_closure() -> impl Fn(i32) -> i32 {
|x| x + 1
}
17 changes: 14 additions & 3 deletions src/ch19-05-advanced-functions-and-closures.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,26 @@ The compiler error is as follows:
```

The error references the `Sized` trait again! Rust doesn’t know how much space
it will need to store the closure. We saw a solution to this problem earlier.
it will need to store the closure. We saw some solutions to this problem earlier.

We can use a trait object:

```rust,noplayground
{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs}}
```

This code will compile just fine. For more about trait objects, refer to the
(For more about trait objects, refer to the
section [“Using Trait Objects That Allow for Values of Different
Types”][using-trait-objects-that-allow-for-values-of-different-types]<!--
ignore --> in Chapter 17.
ignore --> in Chapter 17.)

Or we can use the [`impl Trait` return type syntax][returning-types-that-implement-traits]<!-- ignore -->:

```rust,noplayground
{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-23-returns-closure-impl-trait/src/lib.rs}}
```

Either of these snippets will compile just fine.

Next, let’s look at macros!

Expand All @@ -128,3 +137,5 @@ ch19-03-advanced-traits.html#advanced-traits
[enum-values]: ch06-01-defining-an-enum.html#enum-values
[using-trait-objects-that-allow-for-values-of-different-types]:
ch17-02-trait-objects.html#using-trait-objects-that-allow-for-values-of-different-types
[returning-types-that-implement-traits]:
ch10-02-traits.html#returning-types-that-implement-traits