Skip to content

Commit 6377cb0

Browse files
committed
Fix rust-lang#1060: add page on Impl Trait
1 parent 37a2861 commit 6377cb0

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@
137137
- [Operator Overloading](trait/ops.md)
138138
- [Drop](trait/drop.md)
139139
- [Iterators](trait/iter.md)
140+
- [impl Trait](trait/impl_trait.md)
140141
- [Clone](trait/clone.md)
141142

142143
- [macro_rules!](macros.md)

src/trait/impl_trait.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# impl Trait
2+
3+
If your function returns a type that implements `MyTrait`, you can write its return type as `-> impl MyTrait`. This can help simplify your type signatures quite a lot!
4+
5+
```rust,editable
6+
use std::iter;
7+
use std::vec::IntoIter;
8+
9+
// This function combines two Vec<i32> and returns an iterator over it.
10+
// Look how complicated its return type is!
11+
fn combine_vecs_explicit_return_type<'a>(
12+
v: Vec<i32>,
13+
u: Vec<i32>,
14+
) -> iter::Cycle<iter::Chain<IntoIter<i32>, IntoIter<i32>>> {
15+
v.into_iter().chain(u.into_iter()).cycle()
16+
}
17+
18+
// This is the exact same function, but its return type uses `impl Trait`.
19+
// Look how much simpler it is!
20+
fn combine_vecs<'a>(
21+
v: Vec<i32>,
22+
u: Vec<i32>,
23+
) -> impl Iterator<Item=i32> {
24+
v.into_iter().chain(u.into_iter()).cycle()
25+
}
26+
```
27+
28+
More importantly, some Rust types can't be written out. For example, every closure has its own unnamed concrete type. Before `impl Trait` syntax, you couldn't write a function like this:
29+
30+
```rust,editable
31+
fn return_closure() -> impl Fn(i32) {
32+
let closure = |x: i32| { println!("the value of x is {}", x) };
33+
closure
34+
}
35+
```
36+
37+
Here's a more realistic example: what if you want to return an iterator that uses `map` or `filter` closures? Because the closure's types don't have names, you can't write out an explicit return type. But with `impl Trait` you can do this easily:
38+
39+
```rust,editable
40+
fn double_positives<'a>(numbers: &'a Vec<i32>) -> impl Iterator<Item = i32> + 'a {
41+
numbers
42+
.iter()
43+
.filter(|x| x > &&0)
44+
.map(|x| x * 2)
45+
}
46+
```

0 commit comments

Comments
 (0)