简体   繁体   English

如何在Rust中实现特征对象?

[英]How are trait objects implemented in Rust?

I'm trying to understand how trait objects are implemented in Rust. 我试图了解如何在Rust中实现特征对象。 Please let me know if the following understanding is correct. 如果以下理解正确,请告诉我。

I have a function that takes any type that implements the Write trait: 我有一个函数,可以采用实现Write特征的任何类型:

fn some_func(write_to: &mut Write) {}

In any place where we have a type that implements this trait and calls the above function, the compiler generates a "trait object", probably by adding a call to TraitObject::new(data, vtable) . 在我们拥有实现该特征并调用上述函数的类型的任何地方,编译器都可能通过向TraitObject::new(data, vtable)添加调用来生成“特征对象”。

If we have something like: 如果我们有这样的事情:

let input = get_user_input(); // say we are expecting the input to be 1 or 2
let mut file = File::new("blah.txt").unwrap();
let mut vec: Vec<u8> = vec![1, 2, 3];

match input {
    1 => some_func(&mut file),
    2 => some_func(&mut vec),
}

will probably turn out to be: 可能会变成:

match input {
    1 => {
        let file_write_trait_object: &mut Write =
            TraitObject::new(&file, &vtable_for_file_write_trait);
        some_func(file_write_trait_object);
    }
    2 => {
        let vec_write_trait_object: &mut Write =
            TraitObject::new(&vec, &vtable_for_vec_write_trait);
        some_func(vec_write_trait_object);
    }
}

Inside some_func the compiler will just access the methods used based on the vtable in the TraitObject passed along. some_func内部,编译器将仅访问基于传递的TraitObject基于vtable的方法。

特性对象是胖指针,因此fn some_func(write_to: &mut Write)编译为类似fn some_func(_: *mut OpaqueStruct, _: *const WriteVtable)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM