TIL; we can add where clauses in struct definitions
Hello there,
Today I found myself writing something I thought would never compile, but ended up being a great pattern I discovered and I wanted to know if it's common, and how you guys feel about it.
It is possible to add where clauses to struct definitions, restricting the struct itself just like so :
struct MyStruct<T> where MyStruct<T>: CanBeBuilt {
data: T,
}
trait CanBeBuilt {}
This enforce the generic struct to provide an implementation for some trait, or it can't be constructed at all. So the following :
fn main() {
let my_struct: MyStruct<u8> = MyStruct {
data: 0,
};
}
Does not compile, until we add the implementation:
impl CanBeBuilt for MyStruct<u8> {}
Obviously with this empty trait this adds nothing, but I find this really interesting. Was this designed or did it emerged from the rust type system ?
How could you see yourself use this ? Have you ever used it already ?