官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 融水| 光山县| 托克逊县| 肇州县| 霸州市| 巴东县| 基隆市| 长兴县| 青神县| 南涧| 金阳县| 达孜县| 四川省| 梧州市| 桑日县| 宁蒗| 宝鸡市| 景洪市| 东乡| 叙永县| 潢川县| 金华市| 精河县| 会同县| 清流县| 丘北县| 牟定县| 安达市| 镇原县| 时尚| 连江县| 来宾市| 卢湾区| 永吉县| 文山县| 泗水县| 璧山县| 安宁市| 济阳县| 毕节市| 监利县|