You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Let's first look at the problem this feature attempts to solve.
For example, I got a type named Cat and a type named Lion both Lion and Cat implement the traits HasName and HasMeow.
I need to create a Vec of references to types that implement both HasName and HasMeow.
As far as I know (and I may be very wrong) this is how you would do that.
//lion is of type Lion , cat is of type Cat.
trait HasBothMeowAndName : HasMeow + HasName {};
impl HasBothMeowAndName for Cat{}
impl HasBothMeowAndName for Lion{}
let vector : Vec<&dyn HasBothMeowAndName> = vec![&lion,&cat];
dyn bounds is a syntax sugar feature attempting to make this ugly code more readable and easier to write.
Simply do let vector : Vec<&dyn (HasName + HasMeow)> = vec![&lion,&cat];
The code will compile since both Lion and Cat implement the traits HasName and HasMeow.
Of course, you'll be able to use the functions of the traits on every element of the vector.
for entity in vector {
entity.meow();
entity.get_name();
}
*The dyn bounds feature isn't limited to the Vec struct.
*You can add more than two traits using the Add operator.
example: dyn (Trait1 + Trait2 + Trait3 + Trait4)
Readable intuitive and useful.
The text was updated successfully, but these errors were encountered:
*Note: Syntax feedback is welcomed.
Let's first look at the problem this feature attempts to solve.
For example, I got a type named
Cat
and a type namedLion
bothLion
andCat
implement the traitsHasName
andHasMeow
.I need to create a Vec of references to types that implement both
HasName
andHasMeow
.As far as I know (and I may be very wrong) this is how you would do that.
dyn bounds is a syntax sugar feature attempting to make this ugly code more readable and easier to write.
Simply do
let vector : Vec<&dyn (HasName + HasMeow)> = vec![&lion,&cat];
The code will compile since both
Lion
andCat
implement the traitsHasName
andHasMeow
.Of course, you'll be able to use the functions of the traits on every element of the vector.
*The dyn bounds feature isn't limited to the Vec struct.
*You can add more than two traits using the Add operator.
example:
dyn (Trait1 + Trait2 + Trait3 + Trait4)
Readable intuitive and useful.
The text was updated successfully, but these errors were encountered: