Home > Net >  Why does Rust add a generic type definition after the method name?
Why does Rust add a generic type definition after the method name?

Time:11-04

I found the following code in the official rust documentation and I was wondering about the purpose of the generic declaration in mixup<V, W>:

impl<T, U> Point<T, U> {
    fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
        Point {
            x: self.x,
            y: other.y,
        }
    }
}

I understand that the generic definition impl<T, U> is used to ensure that the implementation of the Point struct matches all generic types. But what is the purpose of the generic definition in mixup<V, W> bit? It just seems like meaningless code since the return type and parameter generics are clearly defined, so what other purpose could it have? The documentation doesn't address this whatsoever.

Here is the link to the documentation: Rust Official Documentation Chap 10

CodePudding user response:

The answer is in the text you link:

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).

The types V and W may be different than T and U. mixup takes a Point<T,U> (which is self) and a Point<V,W>, and returns a Point<T,W>, replacing the y:U property with a y:W property. The example code shows what it's doing. Try removing the <V, W> and you'll see the problem.

When you say "the return type and parameter generics are clearly defined," they're only defined because of that <V,W>.

  • Related