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

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.

主站蜘蛛池模板: 岳池县| 中宁县| 亳州市| 荣昌县| 白朗县| 潼关县| 福建省| 兴业县| 镇巴县| 元阳县| 绥阳县| 西宁市| 安宁市| 兴安县| 利辛县| 宣恩县| 新化县| 太湖县| 乌什县| 南部县| 方城县| 鸡泽县| 田阳县| 萍乡市| 内丘县| 鄄城县| 和顺县| 巩留县| 昭苏县| 珲春市| 招远市| 宜良县| 武穴市| 芜湖县| 闵行区| 项城市| 怀仁县| 马尔康县| 永吉县| 怀化市| 自贡市|