Operator expressions

Again, like math, Rust has a number of symbolic operators that can be applied to values to transform them into some new value. For example, + is a Rust operator that adds two values together. So, 2 + 2 is a Rust expression adding the number 2 to itself, producing the number 4. Rust also uses - as the subtraction operator, * as the multiplication operator, / as the division operator, and % as the remainder operator.

Rust is not limited to mathematical operators, though. In Rust, & means and, | means or, ^ means exclusive or, ! means not (!true is false, for example), << means leftward bit shift, and >> means rightward bit shift. Sometimes the meanings of those operations depends on the type of value that they're acting on. For example, | means bitwise or when applied to integers, but logical or when applied to Boolean values.

Then there are the comparison operators. The == operator means check whether two values are equal. An expression built around the == operator produces the Boolean value true if the two values being compared are equal, and false if they are not. So, for example, 5 == 4 is an expression producing false as its result. Similarly, != means not equal, > means greater than, < means less than, >= means greater than or equal, and <= means less than or equal. All of them produce true when the relationship is correct, and false when it is not.

Finally, Rust recognizes && and || operators. These can only be applied to Boolean (true or false) values, and produce the same results as & and | do when applied to the same values. The difference is that && and || are what is called lazy or short-circuit operators, which means that they will not bother evaluating their right-side operand if the left-side operand provides enough information to determine the operator's produced value. For example, for the expression false && some_expensive_calculation(), Rust will never bother to run the some_expensive_calculation function, because no matter what the function produced as its result, the result of the && operation is going to be false.

In most situations where we'd use & or | on Boolean values, we should use && or || instead, since it allows Rust to be a little more efficient, especially if we're mindful enough to put the more expensive operations on the right side of the operator.

These are not a full list of Rust's operators, and we'll see some of the more specialized ones as we move onward through the language. These are the operators we need for expressing the majority of calculations, computations, and decisions in our programs, though.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.237.24