How do you create a Box when T is a trait-object?

后端 未结 3 1867
悲哀的现实
悲哀的现实 2021-01-14 05:42

I have the following code

extern crate rand;
use rand::Rng;

pub struct Randomizer {
    rand: Box,
}

impl Randomizer {
    fn new() -> Self {         


        
3条回答
  •  时光说笑
    2021-01-14 06:34

    I also want to post the answer, that one way to deal with this situation is

    fn with_rng(rng: &TRand) -> Self {
        let r = Box::new(*rng);
        Randomizer { rand: r }
    }
    

    Rust's monomorphism will create the necessary implementation of with_rng replacing TRand by a concrete sized type. In addition, you may add a trait bound requiring TRand to be Sized.

提交回复
热议问题