1

I have a binding to a trait, and I want to cast it to the implementing struct so that I can call a method implemented on that struct. Is this possible? Below is code that illustrates what I'd like to do:

struct Struct {
    num: u8
}

trait Trait {
    fn trait_fn(&self) -> u8;
}

impl Trait for Struct {
    fn trait_fn(&self) -> u8 {
        self.num + 1
    }
}

impl Struct {
    fn struct_fn(&self) -> u8 {
        self.num - 1
    }
}

fn main() {
    let t: Box<Trait> = Box::new(Struct { num: 5 });
    let t_result = t.trait_fn();
    let s_result = (*t as Struct).struct_fn(); // How can I do something like this?
    println!("Trait Result: {}, Struct Result: {}", t_result, s_result);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
w.brian
  • 16,296
  • 14
  • 69
  • 118
  • 5
    This is called "downcasting" and isn't really available. This will be a duplicate of http://stackoverflow.com/q/27892375/155423 or http://stackoverflow.com/q/25246443/155423. – Shepmaster Nov 07 '15 at 20:13
  • 2
    BTW: In some situations it is helful to use an enum rather than a trait. This allows you to use match instead of downcasting. https://doc.rust-lang.org/book/enums.html – nielsle Nov 08 '15 at 14:51

0 Answers0