9.11 Generic Structs

9.11.1 Defining Generic Structs

You can define structs that are generic over types.

#![allow(unused)]
fn main() {
struct Point<T> {
    x: T,
    y: T,
}
}

9.11.2 Using Generic Structs

struct Point<T> {
    x: T,
    y: T,
}
fn main() {
    let integer_point = Point { x: 5, y: 10 };
    let float_point = Point { x: 1.0, y: 4.0 };
}
  • The type T is determined when the struct is instantiated.

9.11.3 Methods on Generic Structs

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}
  • You can implement methods for generic structs.