0

So, I basically have an enum and a struct:

enum tonsTypes
{
    TotalSum(String),
    Batches(Vec<String>)
}

struct Duo
{
    name:String,
    tons: tonsTypes
}

Then, I have a du = Vec<Duo> where Duo.tons can be either String or Vec<String>. Is there any way of finding out what each duo[i].tons is? Is it a String or a Vec<String>?

I want to do something like:

 for x in duo
    if (//if x.tons is of type String)
    then do this ...
    else //(if it is of type Vec<String>)
    then do this..

.

Thank you!

brewandrew
  • 156
  • 9

1 Answers1

0

You can do it like this:

enum tonsTypes
{
    TotalSum(String),
    Batches(Vec<String>)
}

struct Duo
{
    name:String,
    tons: tonsTypes
}

fn main() {
    let duos = vec![
        Duo{
            name: "Test1".to_string(),
            tons: tonsTypes::TotalSum("TotalSum".to_string())
        },
        Duo{
            name: "Test2".to_string(),
            tons: tonsTypes::Batches(vec!["Batch1".to_string(), "Batch2".to_string()])
        }
    ];
    
    let mut iter = duos.iter();
    match_value(&iter.next().unwrap().tons);
    match_value(&iter.next().unwrap().tons);
}

fn match_value(value: &tonsTypes){
    match value {
        tonsTypes::TotalSum(value) => print_type_of(value),
        tonsTypes::Batches(value) => print_type_of(value),
    }
}

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

Playground link.

However Rust does not really provide a way to retrieve the type and this should not be depended on: https://stackoverflow.com/a/58119924/4593433

If you only want to use the type of the enum value for checking something it is better to simply check for that value, because you already know the assigned data type then. So basically do this instead:

for x in duo
    if (x.tons == tonsTypes::TotalSum)
        //then do this ...
    else (x.tons == tonsTypes::Batches)
        //then do this..
frankenapps
  • 5,800
  • 6
  • 28
  • 69