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

Clarify generic types #2895

Merged
merged 1 commit into from
Nov 14, 2021
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
struct Point<T, U> {
x: T,
y: U,
struct Point<X1, Y1> {
x: X1,
y: Y1,
}

impl<T, U> Point<T, U> {
fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
impl<X1, Y1> Point<X1, Y1> {
fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
Point {
x: self.x,
y: other.y,
Expand Down
15 changes: 7 additions & 8 deletions src/ch10-01-syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,11 @@ point is from the point at coordinates (0.0, 0.0) and uses mathematical
operations that are available only for floating point types.

Generic type parameters in a struct definition aren’t always the same as those
you use in that struct’s method signatures. For example, Listing 10-11 defines
the method `mixup` on the `Point<T, U>` struct from Listing 10-8. The method
takes another `Point` as a parameter, which might have different types from the
`self` `Point` we’re calling `mixup` on. The method creates a new `Point`
instance with the `x` value from the `self` `Point` (of type `T`) and the `y`
value from the passed-in `Point` (of type `W`).
you use in that struct’s method signatures.
Listing 10-11 uses the generic types `X1` `Y1` for the `Point` struct and
`X2` `Y2` for the `mixup` method signature to make the example clearer.
The method creates a new `Point` instance with the `x` value from the `self`
`Point` (of type `X1`) and the `y` value from the passed-in `Point` (of type `Y2`).

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

Expand All @@ -260,8 +259,8 @@ call will print `p3.x = 5, p3.y = c`.

The purpose of this example is to demonstrate a situation in which some generic
parameters are declared with `impl` and some are declared with the method
definition. Here, the generic parameters `T` and `U` are declared after `impl`,
because they go with the struct definition. The generic parameters `V` and `W`
definition. Here, the generic parameters `X1` and `Y1` are declared after `impl`,
because they go with the struct definition. The generic parameters `X2` and `Y2`
are declared after `fn mixup`, because they’re only relevant to the method.

### Performance of Code Using Generics
Expand Down