72

最近的 Rust 更改使“特征对象”对我来说更加突出,但我对究竟是什么使某些东西成为特征对象只有模糊的把握。一个特别的变化是即将到来的变化,允许 trait 对象将 trait 实现转发到内部类型。

给定一个 trait Foo,我很确定Box<Foo>/Box<dyn Foo>是一个 trait 对象。&Foo/&dyn Foo也是一个特征对象吗?像Rcor之类的其他智能指针Arc呢?我怎样才能使自己的类型算作 trait 对象?

参考文献只提到了一次 trait 对象,但没有像定义一样。

4

3 回答 3

97

当你有一个指向特性的指针时,你就有了特性对象。 Box, Arc,Rc和引用&的核心都是指针。在定义“特征对象”方面,它们以相同的方式工作。

“特征对象”是 Rust 对动态调度的看法。这是一个示例,我希望它有助于展示 trait 对象是什么:

// define an example struct, make it printable
#[derive(Debug)]
struct Foo;

// an example trait
trait Bar {
    fn baz(&self);
}

// implement the trait for Foo
impl Bar for Foo {
    fn baz(&self) {
        println!("{:?}", self)
    }
}

// This is a generic function that takes any T that implements trait Bar.
// It must resolve to a specific concrete T at compile time.
// The compiler creates a different version of this function
// for each concrete type used to call it so &T here is NOT
// a trait object (as T will represent a known, sized type
// after compilation)
fn static_dispatch<T>(t: &T)
where
    T: Bar,
{
    t.baz(); // we can do this because t implements Bar
}

// This function takes a pointer to a something that implements trait Bar
// (it'll know what it is only at runtime). &dyn Bar is a trait object.
// There's only one version of this function at runtime, so this
// reduces the size of the compiled program if the function
// is called with several different types vs using static_dispatch.
// However performance is slightly lower, as the &dyn Bar that
// dynamic_dispatch receives is a pointer to the object +
// a vtable with all the Bar methods that the object implements.
// Calling baz() on t means having to look it up in this vtable.
fn dynamic_dispatch(t: &dyn Bar) {
    // ----------------^
    // this is the trait object! It would also work with Box<dyn Bar> or
    // Rc<dyn Bar> or Arc<dyn Bar>
    //
    t.baz(); // we can do this because t implements Bar
}

fn main() {
    let foo = Foo;
    static_dispatch(&foo);
    dynamic_dispatch(&foo);
}

为了进一步参考,Rust book 中有一个很好的 Trait Objects 章节

于 2014-12-19T16:27:41.987 回答
9

简短回答:您只能将对象安全的特征转换为特征对象。

对象安全特征:不能解析为具体实现类型的特征。在实践中,两个规则控制一个特征是否是对象安全的。

  1. 返回类型不是 Self。
  2. 没有泛型类型参数。

任何满足这两个规则的特征都可以用作特征对象。

对象安全的特征示例可用作特征对象

trait Draw {
    fn draw(&self);
}

不能用作特征对象的特征示例:

trait Draw {
    fn draw(&self) -> Self;
}

详细解释:https ://doc.rust-lang.org/book/second-edition/ch17-02-trait-objects.html

于 2018-07-23T20:01:33.613 回答
2

特征对象是动态调度的 Rust 实现。动态分派允许在运行时选择多态操作(特征方法)的一种特定实现。动态调度允许非常灵活的架构,因为我们可以在运行时交换函数实现。但是,与动态调度相关的运行时成本很小。

保存特征对象的变量/参数是胖指针,由以下组件组成:

  • 指向内存中对象的指针
  • 指向该对象的 vtable 的指针,vtable 是一个带有指向实际方法实现的指针的表。

例子

struct Point {
    x: i64,
    y: i64,
    z: i64,
}

trait Print {
    fn print(&self);
}

// dyn Print is actually a type and we can implement methods on it
impl dyn Print + 'static {
    fn print_traitobject(&self) {
        println!("from trait object");
    }
}

impl Print for Point {
    fn print(&self) {
        println!("x: {}, y: {}, z: {}", self.x, self.y, self.z);
    }
}

// static dispatch (compile time): compiler must know specific versions
// at compile time generates a version for each type

// compiler will use monomorphization to create different versions of the function
// for each type. However, because they can be inlined, it generally has a faster runtime
// compared to dynamic dispatch
fn static_dispatch<T: Print>(point: &T) {
    point.print();
}

// dynamic dispatch (run time): compiler doesn't need to know specific versions
// at compile time because it will use a pointer to the data and the vtable.
// The vtable contains pointers to all the different different function implementations.
// Because it has to do lookups at runtime it is generally slower compared to static dispatch

// point_trait_obj is a trait object
fn dynamic_dispatch(point_trait_obj: &(dyn Print + 'static)) {
    point_trait_obj.print();
    point_trait_obj.print_traitobject();
}

fn main() {
    let point = Point { x: 1, y: 2, z: 3 };

    // On the next line the compiler knows that the generic type T is Point
    static_dispatch(&point);

    // This function takes any obj which implements Print trait
    // We could, at runtime, change the specfic type as long as it implements the Print trait
    dynamic_dispatch(&point);
}
于 2020-12-28T11:54:03.773 回答