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.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
// 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:
0 commit comments