Is it possible to overload a function with different numbers of arguments (using traits)

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.

enum MixedInts {
    SmallInt(i32),
    TwoSmallInts(i32, i32),
}

trait IntoMixedInts {
    fn into(self) -> MixedInts;
}

impl MixedInts {
    fn new<A>(args: A) -> MixedInts
        where A: IntoMixedInts
    {
        args.into()
    }
}

impl IntoMixedInts for i32 {
    fn into(self) -> MixedInts {
        MixedInts::SmallInt(self)
    }
}

impl IntoMixedInts for (i32, i32) {
    fn into(self) -> MixedInts {
        MixedInts::TwoSmallInts(self.0, self.1)
    }
}

fn main() {
    let x = MixedInts::new(2i32);
    let y = MixedInts::new((2i32, 2i32));
}

Note: In this example, you could use the standard From and Into 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).

enum MixedInts {
    SmallInt(i32),
    TwoSmallInts(i32, i32),
}

impl MixedInts {
    fn new<A>(args: A) -> MixedInts
        where A: Into<MixedInts>
    {
        args.into()
    }
}

impl From<i32> for MixedInts {
    fn from(a: i32) -> MixedInts {
        MixedInts::SmallInt(a)
    }
}

impl From<(i32, i32)> for MixedInts {
    fn from((a, b): (i32, i32)) -> MixedInts {
        MixedInts::TwoSmallInts(a, b)
    }
}

fn main() {
    let x = MixedInts::new(2i32);
    let y = MixedInts::new((2i32, 2i32));
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)