Skip to content
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

traits as parameters: Use references instead of moving the values #2239

Merged
merged 1 commit into from Apr 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
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