Skip to content

Added example of impl Trait as an argument #1468

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

Merged
merged 1 commit into from
Oct 13, 2021
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
51 changes: 51 additions & 0 deletions src/trait/impl_trait.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,56 @@
# `impl Trait`

`impl Trait` can be used in two locations:

1. as an argument type
2. as a return type

## As an argument type

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.

For example, consider the following code:

```rust,editable
fn parse_csv_document<R: std::io::BufRead>(src: R) -> std::io::Result<Vec<Vec<String>>> {
src.lines()
.map(|line| {
// For each line in the source
line.map(|line| {
// If the line was read successfully, process it, if not, return the error
line.split(',') // Split the line separated by commas
.map(|entry| String::from(entry.trim())) // Remove leading and trailing whitespace
.collect() // Collect all strings in a row into a Vec<String>
})
})
.collect() // Collect all lines into a Vec<Vec<String>>
}
```

`parse_csv_document` is generic, allowing it to take any type which implements BufRead, such as `BufReader<File>` or `[u8]`,
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

```rust,editable
fn parse_csv_document(src: impl std::io::BufRead) -> std::io::Result<Vec<Vec<String>>> {
src.lines()
.map(|line| {
// For each line in the source
line.map(|line| {
// If the line was read successfully, process it, if not, return the error
line.split(',') // Split the line separated by commas
.map(|entry| String::from(entry.trim())) // Remove leading and trailing whitespace
.collect() // Collect all strings in a row into a Vec<String>
})
})
.collect() // Collect all lines into a Vec<Vec<String>>
}
```

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


## As a return type

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!

Expand Down