mozilla/rust — Issue #1838: pseudo-overloading functions with enums
Author: erickt
Created: 2012-02-14 05:46:13+00:00
State: open

I've been working on a couple different serialization libraries, and I often find taking advantage of enum variants living in a different namespace than types. It's really nice to declare:

enum t {
int(int),
str(str),
vec([t]),
}

fun to_str(x: t) {
alt x {
int(i) { int::to_str(i) }
str(s) { s }
vec(v) { "[" + str::concat(vec::map(v, to_str), ",") + "]" }
}
}

But calling these functions can get a bit noisy, especially when using arrays:

to_str(vec([int(1), str("foo"), vec([int(2), str("bar")])]))

I'm not sure if we're planning on supporting overloading functions, but what if the type system could automatically box arguments if an enum name is the same as the type? As in allowing us to write:

to_str([1, "foo", [2, "bar"]])

and automatically convert it to the boxed form from above. I'm not sure if this would play well with generics or typeclasses, but it'd really clean up some code I'm writing. Is this possible, or even a good idea?