Guard Condition
In a match
expression, you can add extra conditions to a pattern on the left of =>
using the if
keyword. This feature is called a guard condition. A guard condition allows you to refine the matching process by adding additional boolean expressions that must evaluate to true
for the pattern to be considered a match.
In function validate
, we use a guard condition to ensure the string in the option is not empty:
-
If the option is
Some(path)
andpath
is not an empty string, thematch
expression evaluates totrue
. -
If the option is
Some(path)
butpath
is an empty string, the pattern guard fails, and the second case with the wildcard pattern_
is matched instead. Thematch
expression evaluates tofalse
. -
If the option is
None
, the wildcard pattern_
is matched, and thematch
expression evaluates tofalse
.
///|
fn validate(path : String?) -> Bool {
match path {
Some(path) if path != "" => true
_ => false
}
}
///|
fn main {
let path1 = Some("/home/config")
let path2 = Some("")
let path3 = None
println(validate(path1))
println(validate(path2))
println(validate(path3))
}