jeudi 22 octobre 2020

is it possible to return a generic struct with a random type from a function

Im not certain what i want to do is possible but hopefully someone comes up with a solution. I have a struct:

pub struct VirtType<T> {
    value: T
}

and i want to generate a random value of a random type to fill this field like so

pub fn random_type() -> VirtType {
    let mut rng = thread_rng();
    match rng.gen_range(0,13) {
        0  => VirtType{value: rng.gen::<bool>()},                   //bool
        1  => VirtType{value: rng.gen::<u8>()},                     //u8
        2  => VirtType{value: rng.gen::<u16>()},                    //u16
        3  => VirtType{value: rng.gen::<u32>()},                    //u32
        4  => VirtType{value: rng.gen::<u64>()},                    //u64
        5  => VirtType{value: rng.gen::<u128>()},                   //u128
        6  => VirtType{value: rng.gen::<i8>()},                     //i8
        7  => VirtType{value: rng.gen::<i16>()},                    //i16
        8  => VirtType{value: rng.gen::<i32>()},                    //132
        9  => VirtType{value: rng.gen::<i64>()},                    //i164
        10 => VirtType{value: rng.gen::<i128>()},                   //i128
        11 => {                                                     //Array<T>
            let t = random_type();
            VirtType{value: (0..rng.gen_range(0,10)).map(|_| t.gen_another(&t)).collect()}
        },                                                          //Tuple(T)
        12 => VirtType{value: (0..rng.gen_range(2,10)).map(|_| random_type()).collect()},
        _  => panic!("Invalid number in random_type")
    }
}

im not the best with generics and, again, i feel like this is probably not going to work because there would be no way to know what the return type would be at compile time. but it would save me a BUNCH of redundancy. any ideas on how to accomplish this?




Aucun commentaire:

Enregistrer un commentaire