Watch 25 Star 65 Fork 17

hainuo / rust ebookRuby

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Without author's permission, this code is only for learning and cannot be used for other purposes.
Clone or download 2.61 KB
Copy Edit Web IDE Raw Blame History
hainuo authored 2015-07-08 22:38 . 语法变量引用

% if if语句

Rust’s take on if is not particularly complex, but it’s much more like the if you’ll find in a dynamically typed language than in a more traditional systems language. So let’s talk about it, to make sure you grasp the nuances.


if is a specific form of a more general concept, the ‘branch’. The name comes from a branch in a tree: a decision point, where depending on a choice, multiple paths can be taken.

if 是一个广泛概念“分支”的一个明确的形式。这个名字来自于一个树状分支,依赖于一个选择点,有多条路径可以选择。

In the case of if, there is one choice that leads down two paths:


let x = 5;

if x == 5 {
    println!("x is five!");

If we changed the value of x to something else, this line would not print.More specifically, if the expression after the if evaluates to true, then the block is executed. If it’s false, then it is not.


If you want something to happen in the false case, use an else:


let x = 5;

if x == 5 {
    println!("x is five!");
} else {
    println!("x is not five :(");

If there is more than one case, use an else if:

如果多余一个条件,请使用else if

let x = 5;

if x == 5 {
    println!("x is five!");
} else if x == 6 {
    println!("x is six!");
} else {
    println!("x is not five or six :(");

This is all pretty standard. However, you can also do this:


let x = 5;

let y = if x == 5 {
} else {
}; // y: i32

Which we can (and probably should) write like this:


let x = 5;

let y = if x == 5 { 10 } else { 15 }; // y: i32

This works because if is an expression. The value of the expression is the value of the last expression in whichever branch was chosen. An if without an else always results in () as the value.


Comment ( 0 )

Sign in for post a comment