Why doesn't Rust support trait object upcasting?

前端 未结 3 829
名媛妹妹
名媛妹妹 2020-11-22 07:34

Given this code:

trait Base {
    fn a(&self);
    fn b(&self);
    fn c(&self);
    fn d(&self);
}

trait Derived : Base {
    fn e(&sel         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 07:55

    I ran into the same wall when I started with Rust. Now, when I think about traits, I have a different image in mind than when I think about classes.

    trait X: Y {} means when you implement trait X for struct S you also need to implement trait Y for S.

    Of course this means that a &X knows it also is a &Y, and therefore offers the appropriate functions. It would require some runtime-effort (more pointer dereferences) if you needed to traverse pointers to Y's vtable first.

    Then again, the current design + additional pointers to other vtables probably wouldn't hurt much, and would allow easy casting to be implemented. So maybe we need both? This is something to be discussed on internals.rust-lang.org

提交回复
热议问题