16

在下面的代码中,不可能从实现相同特征的动态大小类型的引用中获得对特征对象的引用。为什么会这样?如果我可以同时使用两者来调用 trait 方法,这两者&dyn Trait之间到底有什么区别?&(?Sized + Trait)

实现的类型FooTraitContainerTrait可能例如具有type Contained = dyn FooTraittype Contained = T在哪里T实现的具体类型FooTrait。在这两种情况下,获得一个&dyn FooTrait. 我想不出另一种这种方法行不通的情况。为什么在一般情况下这不可能FooTraitContainerTrait

trait FooTrait {
    fn foo(&self) -> f64;
}

///

trait FooTraitContainerTrait {
    type Contained: ?Sized + FooTrait;
    fn get_ref(&self) -> &Self::Contained;
}

///

fn foo_dyn(dyn_some_foo: &dyn FooTrait) -> f64 {
    dyn_some_foo.foo()
}

fn foo_generic<T: ?Sized + FooTrait>(some_foo: &T) -> f64 {
    some_foo.foo()
}

///

fn foo_on_container<C: FooTraitContainerTrait>(containing_a_foo: &C) -> f64 {
    let some_foo = containing_a_foo.get_ref();
    // Following line doesn't work:
    //foo_dyn(some_foo)
    // Following line works:
    //some_foo.foo()
    // As does this:
    foo_generic(some_foo)
}

取消注释该foo_dyn(some_foo)行会导致编译器错误

error[E0277]: the size for values of type `<C as FooTraitContainerTrait>::Contained` cannot be known at compilation time
  --> src/main.rs:27:22
   |
27 |     foo_dyn(contained)
   |             ^^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `<C as FooTraitContainerTrait>::Contained`
   = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
   = help: consider adding a `where <C as FooTraitContainerTrait>::Contained: std::marker::Sized` bound
   = note: required for the cast to the object type `dyn FooTrait`
4

3 回答 3

19

这个问题可以简化为以下简单示例(感谢turbulencetoo):

trait Foo {}

fn make_dyn<T: Foo + ?Sized>(arg: &T) -> &dyn Foo {
    arg
}

乍一看,它确实看起来应该编译,正如您所观察到的:

  • 如果TSized,编译器静态地知道它应该使用什么 vtable 来创建特征对象;
  • 如果Tdyn Foo,则 vtable 指针是引用的一部分,可以直接复制到输出。

但是还有第三种可能性会影响工作:

  • 如果T是一些非大小的类型,即使特征是对象安全的,也没有 vtable fordyn Fooimpl Foo for T

没有 vtable 的原因是因为具体类型的 vtable 假定self指针是细指针。在dyn Trait对象上调用方法时,vtable指针用于查找函数指针,只有数据指针传递给函数。

然而,假设你为一个无大小的类型实现了一个(n object-safe) trait:

trait Bar {}
trait Foo {
    fn foo(&self);
}

impl Foo for dyn Bar {
    fn foo(&self) {/* self is a fat pointer here */}
}

如果 this 有一个vtable impl,它必须接受指针,因为impl可能使用的方法是Bar在 上动态分派的self

这会导致两个问题:

  • 没有地方可以将Barvtable 指针存储在一个&dyn Foo对象中,该对象的大小只有两个指针(数据指针和Foovtable 指针)。
  • 即使你有两个指针,你也不能混合和匹配“胖指针”vtables 和“thin pointer”vtables,因为它们必须以不同的方式调用。

因此,即使dyn Bar实现Foo了,也不可能将 a&dyn Bar变成 a &dyn Foo

尽管切片(另一种未调整大小的类型)不是使用 vtables 实现的,但指向它们的指针仍然很胖,因此同样的限制适用于impl Foo for [i32].

在某些情况下,您可以使用CoerceUnsized(仅在 Rust 1.36 的夜间)来表达诸如“必须强制为&dyn FooTrait”之类的界限。不幸的是,我不知道如何在您的情况下应用它。

也可以看看

于 2019-08-09T14:21:55.067 回答
3

不确定这是否能解决你的具体问题,但我确实用以下技巧解决了我的问题:

我将以下方法添加到FooTrait

fn as_dyn(&self) -> &dyn FooTrait;

无法提供默认 impl (因为它需要Selfbe Sized,但限制FooTrait为 beSized禁止为其创建特征对象......)。

但是,对于所有Sized实现,它都被简单地实现为

fn as_dyn(&self) -> &dyn FooTrait { self }

所以基本上它限制了所有实现的FooTrait大小,除了dyn FooTrait.

在操场上试试

于 2020-05-07T09:49:33.213 回答
3

引用自这个博客,它很好地解释了胖指针。

感谢trentcl将问题简化为:

trait Foo {}

fn make_dyn<T: Foo + ?Sized>(arg: &T) -> &dyn Foo {
    arg
}

这给不同之间带来了怎样的投射?Sized

为了回答这个问题,让我们先看看 Unsized type 的实现Trait

trait Bar {
    fn bar_method(&self) {
        println!("this is bar");
    }
}

trait Foo: Bar {
    fn foo_method(&self) {
        println!("this is foo");
    }
}

impl Bar for u8 {}
impl Foo for u8 {}

fn main() {
    let x: u8 = 35;
    let foo: &dyn Foo = &x;
    // can I do
    // let bar: &dyn Bar = foo;
}

那么,你能做到let bar: &dyn Bar = foo;吗?

// below is all pseudo code
pub struct TraitObjectFoo {
    data: *mut (),
    vtable_ptr: &VTableFoo,
}

pub struct VTableFoo {
    layout: Layout,
    // destructor
    drop_in_place: unsafe fn(*mut ()),
    // methods shown in deterministic order
    foo_method: fn(*mut ()),
    bar_method: fn(*mut ()),
}

// fields contains Foo and Bar method addresses for u8 implementation
static VTABLE_FOO_FOR_U8: VTableFoo = VTableFoo { ... };

从伪代码我们可以知道

// let foo: &dyn Foo = &x;
let foo = TraitObjectFoo {&x, &VTABLE_FOO_FOR_U8};
// let bar: &dyn Bar = foo;
// C++ syntax for contructor
let bar = TraitObjectBar(TraitObjectFoo {&x, &VTABLE_FOO_FOR_U8});

bar类型是,TraitObjectBar不是类型TraitObjectFoo。也就是说,您不能将一种类型的结构分配给另一种不同的类型(在 rust 中,在 C++ 中您可以使用 reinterpret_cast)。

你可以做什么来获得另一个级别的间接

impl Bar for dyn Foo {
...
}

let bar: &dyn Bar = &foo;
// TraitObjectFoo {&foo, &VTABLE_FOO_FOR_DYN_FOO}

同样的事情也适用于 Slice。

铸造不同的解决方法Unsized可以通过这个技巧来完成:

// blanket impl for all sized types, this allows for a very large majority of use-cases
impl<T: Bar> AsBar for T {
    fn as_bar(&self) -> &dyn Bar { self }
}

// a helper-trait to do the conversion
trait AsBar {
    fn as_bar(&self) -> &dyn Bar;
}

// note that Bar requires `AsBar`, this is what allows you to call `as_bar`
// from a trait object of something that requires `Bar` as a super-trait
trait Bar: AsBar {
    fn bar_method(&self) {
        println!("this is bar");
    }
}

// no change here
trait Foo: Bar {
    fn foo_method(&self) {
        println!("this is foo");
    }
}
于 2020-06-07T00:19:44.413 回答