if-let Pattern Matching
if-let is a convenient syntax provided by Cangjie for checking and destructuring values of Option type. The syntax is if (let Some(v) <- opt), and when opt contains a value, the inner value is bound to variable v and that branch executes.
This approach is more concise and safer than first using if to check if it's Some, then manually unpacking. The variable v is only valid within the successfully matched branch, preventing misuse elsewhere.
You can add additional conditions after let pattern using && to form more complex judgments. For example, if (let Some(v) <- opt && v > 0) only executes the branch when opt has a value and that value satisfies the condition. Note that patterns connected with || cannot bind variables.
The code on the right demonstrates basic usage of if-let and condition combinations. Try changing Some(42) to None and observe how the program's execution path changes.
if-let are only valid within the successfully matched branch and cannot be used in the else branch.