Skip to content

Commit 27f1ff5

Browse files
authored
Merge pull request #1468 from sammhicks/master
Added example of `impl Trait` as an argument
2 parents 9a60624 + b809d8b commit 27f1ff5

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/trait/impl_trait.md

+51
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,56 @@
11
# `impl Trait`
22

3+
`impl Trait` can be used in two locations:
4+
5+
1. as an argument type
6+
2. as a return type
7+
8+
## As an argument type
9+
10+
If your function is generic over a trait but you don't mind the specific type, you can simplify the function declaration using `impl Trait` as the type of the argument.
11+
12+
For example, consider the following code:
13+
14+
```rust,editable
15+
fn parse_csv_document<R: std::io::BufRead>(src: R) -> std::io::Result<Vec<Vec<String>>> {
16+
src.lines()
17+
.map(|line| {
18+
// For each line in the source
19+
line.map(|line| {
20+
// If the line was read successfully, process it, if not, return the error
21+
line.split(',') // Split the line separated by commas
22+
.map(|entry| String::from(entry.trim())) // Remove leading and trailing whitespace
23+
.collect() // Collect all strings in a row into a Vec<String>
24+
})
25+
})
26+
.collect() // Collect all lines into a Vec<Vec<String>>
27+
}
28+
```
29+
30+
`parse_csv_document` is generic, allowing it to take any type which implements BufRead, such as `BufReader<File>` or `[u8]`,
31+
but it's not important what type `R` is, and `R` is only used to declare the type of `src`, so the function can also be written an
32+
33+
```rust,editable
34+
fn parse_csv_document(src: impl std::io::BufRead) -> std::io::Result<Vec<Vec<String>>> {
35+
src.lines()
36+
.map(|line| {
37+
// For each line in the source
38+
line.map(|line| {
39+
// If the line was read successfully, process it, if not, return the error
40+
line.split(',') // Split the line separated by commas
41+
.map(|entry| String::from(entry.trim())) // Remove leading and trailing whitespace
42+
.collect() // Collect all strings in a row into a Vec<String>
43+
})
44+
})
45+
.collect() // Collect all lines into a Vec<Vec<String>>
46+
}
47+
```
48+
49+
Note that using `impl Trait` as an argument type means that you cannot explicitly state what form of the function you use, i.e. `parse_csv_document::<std::io::Empty>(std::io::empty())` will not work with the second example
50+
51+
52+
## As a return type
53+
354
If your function returns a type that implements `MyTrait`, you can write its
455
return type as `-> impl MyTrait`. This can help simplify your type signatures quite a lot!
556

0 commit comments

Comments
 (0)