I have a struct with generic T for which I want to create a vector of instances of this struct, where for each instance T can be different. I realise I probably need to use a box and possibly need to treat my struct as a trait object, but I am not sure how, since it is not a collection of different structs which implement the same trait, but instead the same struct with a different generic. Below is what I have so far and hopefully illustrates what I am trying to achive, it doesn't work because the dyn keyword seems to expect a trait rather than a generic struct.
struct Point<T> {
x: T,
y: T,
}
struct Points {
points: Vec<Box<dyn Point>>,
}
fn main() {
let points = Points {
points: vec![Point { x: 1, y: 2 }, Point { x: 1.1, y: 2.2 }],
};
}
"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());
}
}
If you're already on nightly, and have the box_syntax
feature enabled, you can also write box Point { x: 1, y: 2 }
to save some boilerplate, although likely not worth switching to nightly for.
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 }),
],
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.