7.9. Rust conditional statement

发布时间 : 2025-10-25 13:33:19 UTC      

Page Views: 9 views

Conditional statements in the Rust language are in this format:

7.9.1. Example #

fn main() { let number = 3; if number < 5 { println!("Condition is true"); } else { println!("Condition is false"); } } 

There are conditions in the above procedure if statement, this syntax is common in many other languages, but there are some differences: first, conditional expressions number < 5 does not need to be included in parentheses (note that it is not allowed); but in Rust if there is no single sentence. {} is not allowed to use a statement instead of a block Nonetheless, Rust supports traditional else-if grammatical:

7.9.2. Example #

fn main() { let a = 12; let b; if a > 0 { b = 1; } else if a < 0 { b = -1; } else { b = 0; } println!("b is {}", b); } 

Running result:

b is 1 

Conditional expressions in Rust must be bool type, for example, the following program is incorrect:

7.9.3. Example #

fn main() { let number = 3; if number { // Error reporting,expected \`bool`, found integerrustc(E0308) println!("Yes"); } } 

Although conditional expressions in the Cripple + language are expressed as integers, either 0 or true, this rule is prohibited in many languages that pay attention to code security.

Combined with the function body expressions learned in the previous chapter,we associate them with:

if <condition> { block 1 } else { block 2 } 

Can the { block 1 } and { block 2 } in this syntax be function body expressions?

The answer is yes! That is, in Rust, we can use the if-else structure to implement expressions similar to ternary conditional operations (A ? B : C) effect:

7.9.4. Example #

fn main() { let a = 3; let number = if a > 0 { 1 } else { -1 }; println!("number 为 {}", number); } 

Running result:

number is 1 

Note: both function body expressions must be of the same type! And there must be one else and the expression blocks that follow.

《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。