Reputation: 3196
I'd like to have a struct, with a member that is a Vec with a Trait Constraint on the types in the Vector. Right now, this is what I am trying:
pub trait SomeTrait {
fn some_function(&self);
}
pub struct SomeStruct<T: SomeTrait> {
member: Vec<T>
}
impl<T: SomeTrait> SomeStruct<T> {
pub fn new() -> SomeStruct<T> {
SomeStruct {
member: Vec::new()
}
}
}
fn main() {
let mut some_struct = SomeStruct::new();
}
And the compiler is giving me:
error: the trait 'sometrait::SomeTrait' is not implemented for the type '_'
let mut some_struct = SomeStruct::new();
^~~~~~~~~~~
note: required by 'somestruct::SomeStruct<T>::new'
let mut some_struct = SomeStruct::new();
^~~~~~~~~~~
I've tried placing <T: SomeTrait>
in various places throughout, but just getting even stranger compiler errors, so those attempts must be way off base.
Thanks in advance for any help!
Upvotes: 2
Views: 2608
Reputation: 59005
The problem is that you haven't given the compiler enough information to figure out what T
is. That's what the _
is for: it's having to infer the parameter to SomeStruct
.
Also, there are no types anywhere in this example that implement SomeTrait
. If you fix both of these problems, it works (with some warnings):
pub trait SomeTrait {
fn some_function(&self);
}
pub struct SomeStruct<T: SomeTrait> {
member: Vec<T>
}
impl<T: SomeTrait> SomeStruct<T> {
pub fn new() -> SomeStruct<T> {
SomeStruct {
member: Vec::new()
}
}
}
impl SomeTrait for i32 {
fn some_function(&self) {}
}
fn main() {
let mut some_struct_a: SomeStruct<i32> = SomeStruct::new();
let mut some_struct_b = SomeStruct::<i32>::new();
}
Upvotes: 2