I can define a struct type that uses a generic type parameter with a trait bound:
struct MyStruct<T: Clone> {
field: T,
}
This prevents me me from instantiating MyStruct
with a generic type which does not meet the trait bound:
// Note: does not implement Clone
struct UnitStruct;
fn main() {
// ERROR: Unsatisfied trait bound: UnitStruct: Clone
let s = MyStruct { field: UnitStruct };
}
But why would I want to define my struct this way? What are the use cases of imposing such limitations on the instantiation of MyStruct
?
I noticed that even with the trait bound in the MyStruct
definition, if I define an interface which uses MyStruct
, I still have to repeat the trait bound:
// This works
fn func<T: Clone>(s: MyStruct<T>) -> T { s.field.clone() }
// This does not. Compiler demands a trait bound for `T`
fn func<T>(s: MyStruct<T>) -> T { s.field.clone() }