Rust match expression

Created By: chatGPT

Rust provides a powerful feature called the match expression that allows you to compare a value against a series of patterns and execute code based on which pattern matches. This is similar to a switch statement in other programming languages but is more flexible and expressive.
let number = 7;

match number {
    1 => println!("One"),
    2 => println!("Two"),
    3 | 4 | 5 => println!("Three, Four, or Five"),
    6..=10 => println!("Six to Ten"),
    _ => println!("Not in the range"),
}

In the example above, the variable number is matched against various patterns:

  • 1, 2: Direct match for these specific values.
  • 3 | 4 | 5: Match for any of these numbers using a bitwise OR.
  • 6..=10: Match for a range of numbers, from 6 to 10 inclusive.
  • _: The catch-all pattern that matches anything not covered by previous patterns.
let match_example = 3;

match match_example {
    1 => println!("Matched One"),
    2 => println!("Matched Two"),
    n if n > 2 => println!("Matched a number greater than two: {}", n),
    _ => println!("Matched something else"),
}
Introduction And SetupVariablesData TypesImmutableMutableIntegerFloating PointBooleanCharacterStringArrayTupleVectorSliceHashmapMethodFunctionSyntaxBlock ExpressionIf ExpressionLoopWhile LoopFor LoopMatch ExpressionPattern MatchingOwnershipBorrowingReferencesLifetimesEnumsStructsTraitsImpl BlockGenericType AliasPanicResultOptionError HandlingUnwrappingVariantClosureIteratorAsyncAwaitTrait ObjectModuleCrateAttributeMacroCommentSingle Line CommentMulti Line CommentDoc CommentCargoFormattingOwnership RulesType InferenceShadowingOperatorArithmetic OperatorComparison OperatorLogical OperatorBitwise OperatorAs KeywordConstStaticCopy TraitClone TraitUnsafe CodeFfiCargo ManagementTraits BoundsMatch ArmDerived TraitsClosure CaptureSplit_atIterFilterMapCollectFrom_iterTuple StructUnit TypeNaming ConventionsModule SystemVisibilityPrivatePublicCrate RootUnix Specific FeaturesWindows Specific Features