The boolean type
is represented by the bool keyword and accepts the values true and
false:
let a = true;
let b = false;
(a, b)(true, false)6.3.1Logical operators¶
Logical operators (see Table 1) combine boolean values to give a new boolean value.
Table 1:Logical operators
Operator | Description |
|---|---|
| NOT |
| AND |
| Short-circuiting AND |
| OR |
| Short-circuiting OR |
| XOR |
The NOT operator ! negates the value:
// don't remove the initial white space
! falsetrueThe AND operator is represented by &:
(false & true, true & true)(false, true)The OR operator is represented by |:
false | truetrueThe XOR operator is represented by ^:
(false ^ true, true ^ true)(true, false)6.3.1.1Short-circuiting operators¶
When combining boolean functions with the AND or OR operator, all functions are always evaluated.
Here are three boolean functions that we will use for demonstrating the way the operators work:
fn foo1() -> bool {
println!("foo1()");
true
}
fn foo2() -> bool {
println!("foo2()");
false
}
fn foo3() -> bool {
println!("foo3()");
true
}Doing an OR operation between them results in the calling of the three
function, despise the fact that he first function foo1() returns true:
let b = foo1() | foo2() | foo3();
println!("{b}");foo1()
foo2()
foo3()
true
Similarly, an AND operation between the same functions triggers the calling
of the three functions while the second one returns false:
let b = foo1() & foo2() & foo3();
println!("{b}");foo1()
foo2()
foo3()
false
To avoid this side effect that can affect performance, two other operators are available. They are called short-circuiting operators:
||is the short-circuiting OR.&&is the short-circuiting AND.
Using the || operator, we that only the first function is evaluated:
let b = foo1() || foo2() || foo3();
println!("{b}");foo1()
true
With the && operator, the last function is not evaluated:
let b = foo1() && foo2() && foo3();
println!("{b}");foo1()
foo2()
false
6.3.2Comparison operators¶
Comparison operators (see Table 2) compare values of various types and return a boolean value.
Table 2:Comparison operators
Operator | Description |
|---|---|
| Nonequality |
| Less than |
| Less than or equal |
| Equality |
| Greater than |
| Greater than or equal |
The equality operator returns true if two values are equal:
(12.2 == 12.3, "abc" == "abc")(false, true)The less than operator return true if one value is strictly smaller than
another:
(12.2 < 12.3, "abc" < "abc", "abc" < "abd")(true, false, true)Other operators are != (inequality), <=, > and >=.