Generic Struct
Define structs with generic type parameters.
Generic Struct
Define structs with generic type parameters.
Difficulty
Intermediate
Code
struct Point<T> {
x: T,
y: T,
}
impl<T: std::fmt::Display> Point<T> {
fn display(&self) {
println!("({}, {})", self.x, self.y);
}
}
fn main() {
let integer_point = Point { x: 5, y: 10 };
let float_point = Point { x: 1.0, y: 4.0 };
integer_point.display();
float_point.display();
}Explanation
Structs can have generic type parameters.
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.