0

In rust I sometimes need to write chained if-else statements. They are not the nicest way to manage multiple conditionals with multiple things to check in the conditions.

Here is an artificial rust-playgroung example of what I mean and in the following code you can see the if-else chain in question.

// see playground for rest of the code

fn check_thing(t: Thing) -> CarryRule {
    let allowed = vec!["birds","dogs","cats","elefants","unknown","veggies","meat"];
    let max_carry_size = 30;
    let max_carry_unknown_size = 3;
    let max_carry_dog_size = 5;
    let typ = &t.typ.as_str();

    if t.size > max_carry_size {
        CarryRule::Forbidden
    } else if ! allowed.contains(typ) {
        CarryRule::Forbidden
    } else if t.typ == "unknown" && t.size > max_carry_unknown_size {
        CarryRule::Forbidden
    } else if t.typ == "dogs" && t.size > max_carry_dog_size {
        CarryRule::Forbidden
    } else if t.typ == "birds" {
        CarryRule::UseCage
    } else {
        CarryRule::UseBox
    }
}

I know, I should use a match statement, but I do not see how I can do all of the checks above using a single match block. I would need to

  • match the t.typ
  • check if the t.size is greater than some value
  • call the allowed.contains(typ) function

I am looking for Rust version of Go's non-parametrized switch-case such as the following.

switch {
case a && b: return 1
case c || d: fallthrough
case e || f: return 2
default:     return 0
}

Of course, I could also refactor the whole example, modelling t.size, t.typ, and the allowed list in a more consistent way that allows nicer match blocks. But sometimes these types are outside of my control and I do not want to wrap the given types in too much extra wrapping.

What are good readable alternatives to such if-else chains with complex conditions in Rust?

2
  • 1
    What have you tried so far with pattern matching in Rust? Is this solution adequate for your problem ? play.rust-lang.org/… Oct 22, 2022 at 11:41
  • @ÖmerErden Thx for this idea. I learned something from this (I am quite new to Rust still). However the required match statements and Thing destructuring do not look much better than the if-else chain. I'd rather go with one of the other proposed solutions.
    – Juve
    Oct 23, 2022 at 13:40

4 Answers 4

3

If you had an enum and a struct you could better handle this:

enum Item {
  Bird,
  Dog,
  Cat,
  Elephant,
  Vegetable,
  Meat,
  Unknown
}

impl Item {
  pub fn can_check(&self) -> bool {
    match self {
      Bird | Cat | Dog => true,
      _ => false
    }
  }
}

So now you can compose a neat container:

struct CarryOn {
  item: Item,
  size: usize,
}

impl CarryOn {
  pub fn can_check(&self) -> CarryRule {
    if !self.item.can_check() {
      return CarryRule::Forbidden;
    }

    match (self.item, self.size) {
      (Item::Unknown, s) if s < max_carry_unknown_size => CarryRule::Forbidden,
      (_,_) => CarryRule::UseBox
    }
  }
}

The idea here is to try and move towards a more Rust-like expression of your situation, and to use the match tool with tuples to cover all your quirky cases as best as possible.

It's also a good idea to try and untangle this into a series of smaller, simpler tests that are easier to understand, like the delegation of can_check().

3
  • This is a bit harder to understand for me as a Rust newbie than the other proposals. But it seems to be the cleanest option. However, I think it is quite a refactoring of the given types. As stated in the question I like to refactor as few given types a possible (e.g., when submitting small patches to an OSS project instead of falling through the door with a big rewrites). Should I "wrap" my given Thing in your CarryOn or just replace it? Also I am missing some of the special rules in your solution. Should I add them in the Impl Item or in the CarryOn match block?
    – Juve
    Oct 23, 2022 at 13:55
  • There's a lot of wiggle room here, and this is really just a first pass at solving the problem. What you might want to do is have a trait that defines a function that expresses if a given item can be carried, or how it must be carried, etc., and implement that for any of the types that you have. You'll know you're heading to a cleaner design when the constraints are expressed in a more succinct container, like instead of max_carry_dog_size you have, as an example, HashSet<Item, usize> for limits, and can do a more generalized lookup on that.
    – tadman
    Oct 23, 2022 at 14:34
  • A lot of your if complexity stems from these seemingly arbitrary tests. If you make them a bit more abstract, more easily configured, the complexity will be minimized, and flexibility will increase. You're defining constraints here, and there's many ways of doing that.
    – tadman
    Oct 23, 2022 at 14:35
1

You can use match guards:

match () {
    () if t.size > max_carry_size => CarryRule::Forbidden,
    () if !allowed.contains(typ) => CarryRule::Forbidden,
    () if t.typ == "unknown" && t.size > max_carry_unknown_size => CarryRule::Forbidden,
    () if t.typ == "dogs" && t.size > max_carry_dog_size => CarryRule::Forbidden,
    () if t.typ == "birds" => CarryRule::UseCage,
    () => CarryRule::UseBox,
}

However, I think it is better to use if-else chains.

3
  • I think this is much more readable as it requires less syntax (no extra curlies, less keywords, less line breaks). Could you elaborate in the answer why you would still recommend if-else over your solution?
    – Juve
    Oct 23, 2022 at 13:59
  • This is a pretty wild use of match and I'm not sure it offers any advantages, certainly not in clarity.
    – tadman
    Oct 23, 2022 at 14:32
  • @Juve Mainly because I don't see it in the wild (as opposed to the same form of Go's switch) and Rust developers will have harder time grasping it. Oct 24, 2022 at 0:41
0

Based on the good recommendations in the other answers, here is a playground with my preferred solution, which uses the following new check_thing function.

const MAX_CARRY_SIZE: usize= 30;
const MAX_CARRY_UNKNOWN_SIZE: usize = 3;
const MAX_CARRY_DOG_SIZE: usize = 5;
const FORBIDDEN: [Typ; 1] = [Typ::Cake];

fn check_thing(t: Thing) -> CarryRule {
    // First apply the general rules and use early returns.
    // This is more readable then if-else-ing all cases from the beginning.
    if t.size > MAX_CARRY_SIZE {
        return CarryRule::Forbidden
    }
    if FORBIDDEN.contains(&t.typ) {
        return CarryRule::Forbidden
    }

    // Match all cases that need special handling using a single `enum`.
    // The rust compiler will help you to have a match for any enum value.
    // Implement special case logic as match guards for the matching enum value.
    match t.typ {
        Typ::Dog if t.size > MAX_CARRY_DOG_SIZE => CarryRule::Forbidden,
        Typ::Unknown if t.size > MAX_CARRY_UNKNOWN_SIZE => CarryRule::Forbidden,
        Typ::Bird => CarryRule::UseCage,
        // use a default for all non-special cases
        _ => CarryRule::UseBox,
    }
}

This solution adopts the proposed enums and match guards but also focusses on readability. It tries to keep all if-else logic in the check_thing function, where it was before. And as before, it applies this logic step by step as it was in the if-else chain.

But let's come back to the original question:

What are good readable alternatives to such if-else chains with complex conditions in Rust?

Here are some options that can help and that can be used complementary.

Match & Guard

Use a simple match statement (one argument only) and implement some of the complexity as match guards. Also, do not use strings for matching, but an enum. This way the rust compiler can help you covering all the logic.

A longer match with a single argument and additional guards can stay quite readable and is the closest you can get if you are looking for something like Go's plain switch.

Split Up

Split up the if-else blocks in separate parts and use early returns instead of adding more else blocks (see the generic and specific parts in the example). If your match guards are too complex find the generic parts and move them up.

Generalize

Express your complex conditions as your object's configuration rather than in long if-else chains. Using a trait or simply adding an enum can help to capture some of the logic and make your entities more configurable.

This kind of refactoring and generalization requires more code changes if you start out with a big complex if-else chain. But it can make your logic configurable and extensible, and may often be the preferred solution if you are the owner of the code base anyway.

Here is this generalized version.


const MAX_CARRY_SIZE: usize= 30;
const MAX_CARRY_UNKNOWN_SIZE: usize = 3;
const MAX_CARRY_DOG_SIZE: usize = 5;

impl Typ {
    pub fn is_carriable(&self) -> bool {
        match self {
            Self::Cake => false,
            _ => true,
        }
    }
    pub fn carry_rule(&self) -> CarryRule {
        match self {
            Self::Bird => CarryRule::UseCage,
            _ => CarryRule::UseBox,
        }
    }
}

impl Thing {
    fn has_allowed_carry_size(&self) -> bool {
        if self.size > MAX_CARRY_SIZE {
            return false
        }
        match self.typ {
            Typ::Dog => self.size <= MAX_CARRY_DOG_SIZE,
            Typ::Unknown => self.size <= MAX_CARRY_UNKNOWN_SIZE,
            _ => true
        }
    }

    pub fn is_carriable(&self) -> bool {
        self.typ.is_carriable() && self.has_allowed_carry_size()
    }

    pub fn carry_rule (&self) -> CarryRule {
        if !self.is_carriable() {
            return CarryRule::Forbidden
        }
        self.typ.carry_rule()
    }
}

pub fn check_thing(t: Thing) -> CarryRule { t.carry_rule() }

As you can see, it separates the Typ and size logic. This has the benefit of making things configurable and reusable, but also has the drawback that the carry logic is now in different places. You can no longer read the rules from top to bottom as in the original if-else block or in my preferred solution at the beginning of the post.

It is up your project requirements which solution you should take.

Finally, thank you for all comments and answers, and for teaching me some more Rust today!

0

I'm very new to Rust, so please someone with more experience correct me if I'm wrong, but another (possibly too simple?) solution for a Go style switch could be to just use true as the match parameter.

For example:

match true {
    true if some_condition => some_value
    true if some_other_condition => some_other_value
    _ => default_value
}
1
  • Yes, as stated in my answer you can use match guards to achieve it. But actually you would want to separate your logic. Handle your generic logic first and use early returns, then do match on real enum value. Rust does not want you not to abuse match syntax. Go encourages you to write big switch blocks for mixed logic of different concerns. Rust does not ;)
    – Juve
    Feb 13 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.