I'm trying to have a new
constructor with one and with two arguments, but I can't seem to figure out how to do this. Is this even possible at the moment?
What I have now gives me an error that multiple applicable items are in scope (playground)
trait __Constructor1<T> {
fn new(T) -> Self;
}
trait __Constructor2<T, U> {
fn new(T, U) -> Self;
}
enum MixedInts {
SmallInt(i32),
TwoSmallInts(i32, i32),
}
impl __Constructor1<i32> for MixedInts {
fn new(__0: i32) -> MixedInts {
MixedInts::SmallInt(__0)
}
}
impl __Constructor2<i32, i32> for MixedInts {
fn new(__0: i32, __1: i32) -> MixedInts {
MixedInts::TwoSmallInts(__0, __1)
}
}
fn main() {
let x = MixedInts::new(2i32);
let y = MixedInts::new(2i32, 2i32);
}
It is technically possible, but not in a way that's practical. You need to use Rust's Universal Function Call Syntax in order for it to disambiguate the calls to
new
.The Iron framework has an interesting Modifier pattern that I think accomplishes what you want. While it's pretty clever, it's ultimately confusing to the user.
Rust doesn't support overloaded functions/methods. As a workaround, you can use tuples to receive multiple values in a single argument. You can then define a trait and implement it for the admissible types of that single argument, and the function will simply delegate to the trait's implementation.
Note: In this example, you could use the standard
From
andInto
traits instead of defining your own trait. It might not work for other traits, though, due to the coherence rules (the rules that ensure that there can only exist one implementation of a certain trait for a certain type).I would suggest making use of the
From
/Into
traits in the standard library.example on Rust Playground