generic
Rust Method-specific type parameters
A method may introduce a new type parameter independent of the parameters on its enclosing impl. This is useful when combining two values with different types. Expected output (not executed): Pens 5 Why: U belongs to pair; T belongs to Shelf. The receiver is consumed. Common mistake: Expecting the method-level U to be available in every other method.
Formal Syntax & Structure
rust syntaxrust
fn method<U>(&self, input: U)Working Example
Example Snippetrust
struct Shelf<T>(T);impl<T> Shelf<T> { fn pair<U>(self, extra: U) -> (T, U) { (self.0, extra) }}fn main() { let (name, count) = Shelf("Pens").pair(5); println!("{name} {count}");}