Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dyn bounds #2748

Closed
tomerze opened this issue Aug 22, 2019 · 2 comments
Closed

dyn bounds #2748

tomerze opened this issue Aug 22, 2019 · 2 comments

Comments

@tomerze
Copy link

tomerze commented Aug 22, 2019

*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 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.

@SimonSapin
Copy link
Contributor

Is this the same as #2035?

@tomerze
Copy link
Author

tomerze commented Aug 22, 2019

@SimonSapin seems like it is. different syntax, same idea. issue closed.

@tomerze tomerze closed this as completed Aug 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants