Skip to content

Commit

Permalink
Clarify generics in method definitions and impls. Fixes #2679.
Browse files Browse the repository at this point in the history
  • Loading branch information
carols10cents committed Nov 14, 2021
1 parent 5c5dbc5 commit 8b09da0
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/ch10-01-syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,13 +210,20 @@ Here, we’ve defined a method named `x` on `Point<T>` that returns a reference
to the data in the field `x`.

Note that we have to declare `T` just after `impl` so we can use it to specify
that we’re implementing methods on the type `Point<T>`. By declaring `T` as a
that we’re implementing methods on the type `Point<T>`. By declaring `T` as a
generic type after `impl`, Rust can identify that the type in the angle
brackets in `Point` is a generic type rather than a concrete type.

We could, for example, implement methods only on `Point<f32>` instances rather
than on `Point<T>` instances with any generic type. In Listing 10-10 we use the
concrete type `f32`, meaning we don’t declare any types after `impl`.
brackets in `Point` is a generic type rather than a concrete type. Because this
is declaring the generic again, we could have chosen a different name for the
generic parameter than the generic parameter declared in the struct definition,
but using the same name is conventional. Methods written within an `impl` that
declares the generic type will be defined on any instance of the type, no
matter what concrete type ends up substituting for the generic type.

The other option we have is defining methods on the type with some constraint
on the generic type. We could, for example, implement methods only on
`Point<f32>` instances rather than on `Point<T>` instances with any generic
type. In Listing 10-10 we use the concrete type `f32`, meaning we don’t declare
any types after `impl`.

<span class="filename">Filename: src/main.rs</span>

Expand Down

0 comments on commit 8b09da0

Please sign in to comment.