Reputation: 1515
How can I define a vector of comparable in Rust?
Say, i32
, i16
...
I tried arr: Vec<Ord>
but the compiler complains about the trait "std::cmp::Ord" cannot be made into an object
Basically I need to store a vector of a vector of comparable objects. e.g.
struct Setup<T: Ord + Copy> {
arr: Vec<Vec<T>>
}
impl<T: Ord + Copy> Setup<T> {
fn new() -> Self {
Self {
arr: vec![
vec![1, 2, 3, 4, 5],
vec![1.0, 2.0, 3.0]
]
}
}
}
Instead of letting the consumer decide what exactly the type is, I would like they can get a vector of comparable stuffs.
Upvotes: 0
Views: 813
Reputation: 161637
The type Vec<Ord>
would be a Vec
where each item is a trait object. What you'd want to do is do Vec<T>
and then set the trait bound on T
to be : Ord
, e.g.
struct Foo<T: Ord> {
arr: Vec<T>,
}
Upvotes: 1