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

后端 未结 2 1999
南旧
南旧 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条回答
  •  旧时难觅i
    2020-12-20 13:59

    Importantly, you don't have to put the generic type behind a reference (like & or Box), you can accept it directly:

    fn myfunction3(v: T) {
        println!("{:?}", v);
    }
    
    fn main() {
        myfunction3(5);
    }
    

    This has the same benefits of monomorphization without the downside of additional memory allocation (Box) or needing to keep ownership of the value somewhere (&).

    I would say that generics should often be the default choice — you only require a trait object when there is dynamic dispatch / heterogeneity.

提交回复
热议问题