Comparison of The Different Conditional Constructs

Use if Statement

  • Use an if statement if:
    • It is desired to test the truthiness of an expression
    • There is a single affirmative test
    • There is a need to evaluate different expressions for each branch
    • It can test expressions based on ranges of values or conditions

Use match Statement

  • Use a match statement if:
    • It is desired to compare multiple possible conditions of an expression
    • The values belong to the same domain
    • It can test expressions based on values only, i.e., condition cannot take ranges

Use if let Statement

  • Use an if let statement if:
    • There is a pattern in the condition and it is to be matched with the scrutinee expression

Last updated 25 Jan 2024, 05:11 +0530 . history