Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Conditional Statements

Rust Conditional Statements

Conditional statements in the Rust language have this format:

Example

fn

main

(

)

{

   

let

number

=

3

;

   

if

number

<

5

{

println

!

(

"Condition is true"

)

;

   

}

else

{

        println

!

(

"Condition is false"

)

;

   

}

}

The above program has a conditional if statement. This syntax is common in many other languages, but there are some differences: first, the conditional expression number < 5 does not need to be enclosed in parentheses (note: "does not need" does not mean "not allowed"); however, in Rust, if does not have the rule that a single statement does not need {}, and a single statement is not allowed to replace a block. Nevertheless, Rust still supports the traditional else-if syntax:

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 为 1

Conditional expressions in Rust must be of type bool. For example, the following program is wrong:

Example

fn

main

(

)

{

   

let

number

=

3

;

   

if

number

{

 

// Error, expected bool, found integerrustc(E0308)

        println

!

(

"Yes"

)

;

   

}

}

Although conditional expressions in C/C++ are represented with integers, where non-zero is true, this rule is forbidden in many languages that emphasize code safety.

Associating with the function-body expressions learned in the previous chapter:

if  { block 1 } else { block 2 } 

In this syntax, the { block 1 } and { block 2 } could be a function-body expression?

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

Example

fn

main

(

)

{

   

let

a

=

3

;

   

let

number

=

if

a

0

{

1

}

else

{

1

}

;

    println

!

(

"number is {}"

,

number

)

;

}

Running result:

number 为 1

Note: The two function-body expressions must have the same type! And there must be an else and its following expression block.