Skip to content

Commit

Permalink
Merge pull request rust-lang#2239 from apatniv/use_references
Browse files Browse the repository at this point in the history
traits as parameters: Use references instead of moving the values
  • Loading branch information
steveklabnik authored Apr 6, 2020
2 parents 34553b9 + 33838c7 commit 2ae0871
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl Summary for Tweet {
}

// ANCHOR: here
pub fn notify(item: impl Summary) {
pub fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}
// ANCHOR_END: here
14 changes: 7 additions & 7 deletions src/ch10-02-traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ syntax sugar for a longer form, which is called a *trait bound*; it looks like
this:

```rust,ignore
pub fn notify<T: Summary>(item: T) {
pub fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
```
Expand All @@ -237,7 +237,7 @@ example, we can have two parameters that implement `Summary`. Using the `impl
Trait` syntax looks like this:

```rust,ignore
pub fn notify(item1: impl Summary, item2: impl Summary) {
pub fn notify(item1: &impl Summary, item2: &impl Summary) {
```

If we wanted this function to allow `item1` and `item2` to have different
Expand All @@ -246,7 +246,7 @@ types, using `impl Trait` would be appropriate (as long as both types implement
only possible to express using a trait bound, like this:

```rust,ignore
pub fn notify<T: Summary>(item1: T, item2: T) {
pub fn notify<T: Summary>(item1: &T, item2: &T) {
```

The generic type `T` specified as the type of the `item1` and `item2`
Expand All @@ -261,13 +261,13 @@ the `notify` definition that `item` must implement both `Display` and
`Summary`. We can do so using the `+` syntax:

```rust,ignore
pub fn notify(item: impl Summary + Display) {
pub fn notify(item: &(impl Summary + Display)) {
```

The `+` syntax is also valid with trait bounds on generic types:

```rust,ignore
pub fn notify<T: Summary + Display>(item: T) {
pub fn notify<T: Summary + Display>(item: &T) {
```

With the two trait bounds specified, the body of `notify` can call `summarize`
Expand All @@ -283,13 +283,13 @@ syntax for specifying trait bounds inside a `where` clause after the function
signature. So instead of writing this:

```rust,ignore
fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {
```

we can use a `where` clause, like this:

```rust,ignore
fn some_function<T, U>(t: T, u: U) -> i32
fn some_function<T, U>(t: &T, u: &U) -> i32
where T: Display + Clone,
U: Clone + Debug
{
Expand Down

0 comments on commit 2ae0871

Please sign in to comment.