2

The following code fails to compile because both X and Y have a function x(). X::f(&n) doesn't work because n is type Box<dyn Y>.

How to call n.(Y::f)() in this situation?

(playground)

trait X {
    fn f(&self) {
        println!("x")
    }
}
trait Y: X {
    fn f(&self) {
        println!("y")
    }
}

impl X for u32 {}
impl Y for u32 {}

fn main() {
    let n: Box<dyn Y> = Box::new(1);
    println!("{:?}", n.f());
}
trent
  • 25,033
  • 7
  • 51
  • 90
jmpq
  • 29
  • 1
  • Does this answer your question? [How do I disambiguate traits in Rust?](https://stackoverflow.com/questions/44953197/how-do-i-disambiguate-traits-in-rust) – Yamirui Sep 04 '20 at 10:53
  • 3
    "*X::f(&n) doesn't work because n is type Box*"—so deref it `X::f(&*n)` ? – eggyal Sep 04 '20 at 10:57
  • X::f(&*n) works! thanks. I didn't know Box can be deref in this way. – jmpq Sep 04 '20 at 11:00
  • 2
    `X::f(n.as_ref())` would also work if you find `&*` a bit too magical (as I do). – user4815162342 Sep 04 '20 at 11:06
  • 5
    Don't do this. This looks like you are trying to do something class-like where `f` in the subclass overrides `f` in the superclass. Traits aren't classes and don't work that way. There should never be any reason for a trait to have a method named the same as another method in a supertrait. – trent Sep 04 '20 at 13:39
  • https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0f7bcdb6fd831bdd28a92e61b34646bb This one? – Sanhu Li Sep 08 '20 at 19:57

0 Answers0