Why doesn't Rust support trait object upcasting?

前端 未结 3 774
名媛妹妹
名媛妹妹 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:49

    As of Jun 2017, the status of this "sub-trait coercion" (or "super-trait coercion") is as follows:

    • An accepted RFC #0401 mentions this as a part of coercion. So this conversion should be done implicitly.

      coerce_inner(T) = U where T is a sub-trait of U;

    • However, this is not yet implemented. There is a corresponding issue #18600.

    There is also a duplicate issue #5665. Comments there explain what prevent this from being implemented.

    • Basically, the problem is how to derive vtables for super-traits. Current layout of vtables is as follows (in x86-64 case):
      +-----+-------------------------------+
      | 0- 7|pointer to "drop glue" function|
      +-----+-------------------------------+
      | 8-15|size of the data               |
      +-----+-------------------------------+
      |16-23|alignment of the data          |
      +-----+-------------------------------+
      |24-  |methods of Self and supertraits|
      +-----+-------------------------------+
      
      It doesn't contain a vtable for a super-trait as a subsequence. We have at least to have some tweaks with vtables.
    • Of course there are ways to mitigate this problem, but many with differing advantages/disadvantages! One has a benefit for the vtable size when there is a diamond inheritance. Another is supposed to be faster.

    There @typelist says they prepared a draft RFC which looks well-organized, but they look like disappeared after that (Nov 2016).

提交回复
热议问题