What is the difference between Box and &Trait / Box?

后端 未结 2 2004
南旧
南旧 2020-12-20 13:23

When writing code with traits you can put the trait in a trait bound:

use std::fmt::Debug;

fn myfunction1(v: Box) {
    println!(\"         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 13:51

    With Box you are using a trait bound to tell the compiler that you want a Box with an instance of some type T which implements Trait, and you will specify T when you use it. The Rust compiler will likely create different, efficient, code for each different T in your code (monomorphization).

    With Box you are telling the compiler that you want a Box with a trait object, a pointer to an unknown type which implements Trait, which means that the compiler will use dynamic dispatch.

    I've included two examples which makes the difference a bit clearer:

    Box, i.e. trait bound:

    use std::fmt::Debug;
    
    struct Wrapper {
        contents: Option>,
    }
    
    impl Wrapper {
        fn new() -> Wrapper {
            Wrapper { contents: None }
        }
    
        fn insert(&mut self, val: Box) {
        }
    }
    
    fn main() {
        let mut w = Wrapper::new();
    
        // makes T for w be an integer type, e.g. Box
        w.insert(Box::new(5));
    
        // type error, &str is not an integer type
        // w.insert(Box::new("hello"));
    }
    

    Box, i.e. trait object:

    use std::fmt::Debug;
    
    struct Wrapper {
        contents: Option>,
    }
    
    impl Wrapper {
        fn new() -> Wrapper {
            Wrapper { contents: None }
        }
    
        fn insert(&mut self, val: Box) {
        }
    }
    
    fn main() {
        let mut w = Wrapper::new();
        w.insert(Box::new(5));
        w.insert(Box::new("hello"));
    }
    

    For further details on the difference between trait bounds and trait objects I recommend the section on trait objects in the first edition of the Rust book.

提交回复
热议问题