Treat generic struct as trait object
"The same struct with a different generic" behaves very similarly to "a different struct". Here, when dealing with trait objects, the concrete type doesn't matter, which is the key idea behind a trait object.
For example:
trait Trait {
fn foo(&self) -> &'static str;
}
struct Point<T> {
x: T,
y: T,
}
// you may have different impls for different generics
impl<T> Trait for Point<T> {
fn foo(&self) -> &'static str {
"a point"
}
}
fn main() {
let points: Vec<Box<dyn Trait>> = vec![
Box::new(Point {x: 1, y: 2}),
Box::new(Point {x: 1.1, y: 2.2}),
Box::new(Point {x: (), y: ()}),
];
for point in points {
println!("{}", point.foo());
}
}
You can wrap the points in an enum
:
struct Point<T> {
x: T,
y: T,
}
struct Points {
points: Vec<PointType>,
}
enum PointType {
U64(Point<u64>),
F32(Point<f32>),
}
fn main() {
let points = Points {
points: vec![
PointType::U64(Point { x: 1, y: 2 }),
PointType::F32(Point { x: 1.1, y: 2.2 }),
],
};
}
Playground