How to override explicitly?


#1

Hi! I have just started to dig in the language. Having Scala as current language in use I’m very excited there are many shared ideas between languages. The question is related to overriding trait function. In Scala you are forced to prepend function definition with override keyword at case ancestor has already got an implementation. This way you are freeing your brain form bothering with typos (that is adding new function instead of overriding one). Is it possible in Rust to express overriding explicitly?


#2

I don’t think overriding is possible. The caller can always be sure of which function they’re calling:

trait A {
    fn a(&self) { println!("a!"); }
}

trait A2: A {
    fn a(&self) { println!("a2!"); }
}

impl A for i32 {}
impl A2 for i32 {}

fn main() {
    //1.a(); // ambiguity
    A::a(&1);
    A2::a(&1);
}

#3

I mean the case when your override a in impl.


#4

You can only implement the methods from the trait, so you can’t add new methods there.


#5

What’s the ancestor to what then? Anyway, a trait implementation can replace the default one and it works in both cases of static and dynamic dispatch (i.e. calling a virtual method).

trait A {
    fn a(&self) { println!("a!"); }
}

impl A for i32 {
    fn a(&self) { println!("surprise!"); }
}

fn main() {
    1.a();
    let x: &A = &1;
    x.a();
}

#6

Aha, i see, thanks! Indeed it doesn’t compile :smile: