Associated traits
Nobody has claimed this yet.
- Dominant language
- Markdown
- Stars
- 6.6k
- Forks
- 1.7k
- Avg merge
- 16h 14m
- Merged PRs (30d)
- 1
Description
RFC 1733 added trait aliases, like:
trait IntoIntIterator = IntoIterator<Item=i32>;
Well, why not allow putting those in traits, by analogy with associated types looking like type aliases? For example:
trait Handler {
trait Arg;
fn handle<ArgImpl: Self::Arg>(&self, arg: ArgImpl);
}
struct MyHandler;
impl Handler for MyHandler {
trait Arg = IntoIterator<Item=i32>;
fn handle<ArgImpl: Self::Arg>(&self, arg: ArgImpl) {
for number in arg { println!("{}", number); }
}
}
Example of a function that's generic over implementations of Handler:
fn example_generic_helper<HandlerImpl, ArgImpl>(handler: HandlerImpl, args: Vec<ArgImpl>)
where HandlerImpl: Handler,
ArgImpl: <HandlerImpl as Handler>::Arg {
for arg in args {
handler.handle(arg);
}
}
Associated traits could also have supertrait bounds.
And if impl Trait syntax is extended to function arguments, they'd be a natural fit:
trait Handler {
trait Arg;
fn handle(&self, arg: impl Self::Arg);
}
(I was just writing some code where this could have come in handy.)
There's also the natural dual of allowing traits as generic parameters, just as associated types mirror regular type parameters and associated consts mirror the upcoming 'const generics'. Something like
fn foo<Impl, trait Trait> where Impl: Trait { … }
I think this has been proposed before.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading RFC 1733 and the examples in this issue, then compare the associated-trait and generic-trait proposals. Done means reaching an agreed RFC-level design that addresses the described syntax, bounds, and implementation implications.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100