-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Delegation #3108
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
Comments
It would be good if you would cross-reference this with any of the previous work done in this area. For example, this RFC on delegation that was closed a few days ago. There's also lots of other related back story. |
That's a good idea, will do. That link seems to take me to a search of open PRs though, I can't see the PR. Perhaps you gave the wrong one? |
Oops: #2393 |
Closing per #3133 (comment) since #2393 was postponed. |
This is a sort of half-RFC draft that I may write into a full RFC if it's a good idea.
Many times, it would be useful if we could delegate in rust - the delegation pattern is good and there are many other uses of it (like in the newtype idiom). Currently, all we can do is implement
Deref
. But this has several disadvantages:Deref
for what it's designed for, we can'tThis is more like extending another class than delegation. So, here's the proposed syntax.
Some notes on this syntax:
by
is a weak keywordCounter
trait and struct, you'd need to update the counter)*
to copy all methods.for
andas
should swap?This
where
clause is similar to that of a generic parameter list in that it just allows for more control/less ugliness.Here's the exact syntax (EBNF):
Motivations
Composition
Currently, there is no struct inheritance in rust - this is a good thing, as you usually favour composition over inheritance. But you still have to refer to the composed object - the methods don't compose. Now you could do:
Newtype
The newtype idiom is very common as we can do various things to a type - implementing a trait or just wrapping around to make a new type (
Days
andMonths
aren't the same even if they are bothi64
). But, like in composition, you still have to call.0
or implementDeref
, neither of which you should have to do.Delegation pattern
This is the basis of the delegation pattern: using public traits to specify your type, then having a private implementation of it and a public creator function. This way, people can easily modify your type and pass their own version without affecting the rest of the code, which doesn't care. We could do:
The text was updated successfully, but these errors were encountered: