Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if both variables are both Some?

Tags:

rust

I am confused about the Some(T) keyword.

I want to check for two variables, if the value is defined (not None). If that is the case, the value of this variables is processed.

I know the match pattern which works like this:

match value {
    Some(val) => println!("{}", val),
    None => return false,
}

If I use this pattern, it will get very messy:

match param {
    Some(par) => {
        match value {
            Some(val) => {
                //process
            },

            None => return false,
        }
    },

    None => return false,
}

This can't be the right solution.

The is a possibility, to ask if the param and value is_some() That would effect code like that:

if param.is_some() && value.is_some() {
    //process
}

But if I do it like that, I always have to unwrap param and value to access the values.

I thought about something like this to avoid that. But this code does not work:

if param == Some(par) && value == Some(val) {
    //process
}

The idea is that the values are accessible by par and val like they are in the match version.

Is there any solution to do something like this?

like image 202
NelDav Avatar asked Apr 06 '20 21:04

NelDav


People also ask

How do you know if two variables are equal?

Use the == operator to test if two variables are equal.

How do you check if two variables are in a list Python?

Check if Variable is a List with type() Now, to alter code flow programatically, based on the results of this function: a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.")

How do you check for multiple equality in Python?

Python Code: x = 20 y = 20 z = 20 if x == y == z == 20: print("All variables have same value!") Sample Output: All variables have same value!

How do you know if three variables are equal?

To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.


Video Answer


1 Answers

If I have several Option values to match, I match on a tuple of the values:

enum Color {
    Red,
    Blue,
    Green,
}

fn foo(a: Option<Color>, b: Option<i32>) {
    match (a, b) {
        (Some(Color::Blue), Some(n)) if n > 10 => println!("Blue large number"),
        (Some(Color::Red), _) => println!("Red number"),
        _ => (),
    }
}

fn main() {
    foo(Some(Color::Blue), None);
    foo(Some(Color::Blue), Some(20));
}         

This allows me to match the combinations that are interesting, and discard the rest (or return false, if that is what you want to do).

like image 132
Mats Kindahl Avatar answered Oct 21 '22 15:10

Mats Kindahl