intermediateGenerics
Multiple Generic Parameters
Use multiple type parameters in functions and structs.
Multiple Generic Parameters
Use multiple type parameters in functions and structs.
Difficulty
Intermediate
Code
rust
use std::fmt::Display;
struct Pair<T, U> {
first: T,
second: U,
}
impl<T: Display, U: Display> Pair<T, U> {
fn new(first: T, second: U) -> Self {
Pair { first, second }
}
fn display(&self) {
println!("({}, {})", self.first, self.second);
}
}
fn zip<T, U>(a: Vec<T>, b: Vec<U>) -> Vec<(T, U)> {
a.into_iter().zip(b).collect()
}
fn main() {
let p = Pair::new(42, "hello");
p.display();
let pairs = zip(vec![1, 2, 3], vec!["a", "b", "c"]);
println!("{:?}", pairs);
}Explanation
Multiple generic parameters with independent bounds.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the generics category to build a complete understanding of this topic.