intermediateGenerics
Generic Struct
Define structs with generic type parameters.
Generic Struct
Define structs with generic type parameters.
Difficulty
Intermediate
Code
rust
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
This example demonstrates how to use generic struct in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the generics category to build a complete understanding of this topic.