RRust By Example
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

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.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Generics Examples