[rust-dev] Functions overloading

Steven Blenkinsop steven099 at gmail.com
Wed Apr 18 17:44:50 PDT 2012


On Wednesday, April 18, 2012, Alexander Stavonin wrote:

> Stefan, I understood you idea but I have problem with compilation.
>
> fn_overloading.rs:31:34: 31:80 error: method `to_input` has an
> incompatible type: type parameter vs int
> fn_overloading.rs:31 impl <t> of to_input<t> for int { fn to_input() ->
> input<int> { ret val(self); } }
>
>  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> Also, am I right that in this case we could not make overloading for
> different types, for example for str and int?
>
> Alexander.
>
>
I think you're looking for:

enum input { int(int), str(str) }

iface to_input { fn to_input() -> input; }
impl of to_input for int { fn to_input() -> input { ret int(self); } }
impl of to_input for str { fn to_input() -> input { ret str(self); } }

fn to_input<T: to_input>(t: T) {
 alt t.to_input() {
int(v) { io::println("int"); }
str(v) { io::println("str"); }
 }
}

fn main() {
to_input(5);
to_input("hello")
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20120418/9b16d68e/attachment.html>


More information about the Rust-dev mailing list