You have to make the varying type the type implementing the trait.
trait Foo {
fn foo(arg: Self, some_int: int);
}
impl<T: Iterator> Foo for T {
fn foo(arg: T, some_int: int) { ... /* arg implements Iterator */ }
}
impl<T: RandomAccessIterator> Foo for T {
fn foo(arg: T, some_int: int) { ... /* arg implements
RandomAccessIterator */ }
}
Although traits are the tool you're supposed to use to do this, there are a
couple issues at the moment:
- The compiler can sometimes get scared and confused when you start mixing
generic impls and concrete impls (or multiple generic impls). This should
be fixed eventually.
- You can only vary on one type. Long term, this can be fixed by making our
traits MultiParameterTypeClasses instead of just regular Type Classes.
Short term, you can avoid this by impl'ing on a tuple of the varying types.
On Thu, May 29, 2014 at 5:52 PM, Tommi <[email protected]> wrote:
> On 2014-05-30, at 3:42, Eric Reed <[email protected]> wrote:
>
> > Rust *does* have function overloading. That's *exactly* what traits are
> for.
> > If you want to overload a function, then make it a trait and impl the
> trait for all the types you want to overload it with.
>
> I've been trying to figure out how exactly to do this. How would I write a
> function that's overloaded based on whether its argument's type implements
> Iterator or RandomAccessIterator?
>
>
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev