[rust-dev] Functions overloading

Stefan Plantikow stefan.plantikow at googlemail.com
Mon Apr 16 17:58:22 PDT 2012


Hi,

Am Donnerstag, 12. April 2012 um 15:47 schrieb Niko Matsakis: 
> Not only that, but it adds an extra layer of complexity for type 
> inferencing, which quite frankly is already complex enough.
> 
> That said, you can do a limited form of overloading using impls:
> 
> impl methods for int {
> fn foo() { ... }
> }
> 
> impl methods for uint {
> fn foo() { ... }
> }
> 
> 

I was reading this again and thought that as a middle ground between type classes and enums, one could use type classes that wrap supported types into enum variants 
for easily switching over them.

enum input<t> { val(t), seq([t]) }

iface to_input<t> { fn to_input() -> input<t> }
impl <t> of to_input<t> for int { fn to_input() -> input<int> { ret val(self); } }
impl <t> of to_input<t> for [int] { fn to_input() -> input<int> { ret seq(self); } }

fn to_input<t>(i: to_input<t>) {
alt i.to_input() {
  val(v) { ... }
  seq(v) { ... }
}
}

This way the user does not have to know about the internal enums and the implementor can simply switch (especially useful with multiple arguments).

I think it would be nice too have some syntax support for building ifaces like that, perhaps via macros.

-- Stefan


More information about the Rust-dev mailing list