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

Branching on a condition

Branching on a condition is done with a common if, if else, or if else if else construct, as in this example:

// from Chapter 3/code/ifelse.rs 
fn main() { 
  let dead = false; 
  let health = 48; 
  if dead { 
    println!("Game over!"); 
       return; 
  } 
  if dead { 
    println!("Game over!"); 
    return; 
  } else { 
    println!("You still have a chance to win!"); 
  } 
  if health >= 50 { 
      println!("Continue to fight!"); 
  } else if health >= 20  { 
      println!("Stop the battle and gain strength!"); 
  } else { 
      println!("Hide and try to recover!"); 
  } 
} 

This gives the following output:

    You still have a chance to win!
    Stop the battle and gain strength!

The condition after the if statement has to be a Boolean. However, unlike in C, the condition must not be enclosed in parentheses. Code blocks surrounded by { } (curly braces) are needed after the if, else, or else if statement. The first example also shows that we can get out of a function with the return value.

Also the if else condition is an expression that returns a value. This value can be used as a function call parameter in a print! statement, or it can be assigned in a let binding, like this:

let active = if health >= 50 { 
           true 
         }else{ 
           false 
         }; 
println!("Am I active? {}", active); 

This prints the following output:

    Am I active? false

The code blocks could contain many lines, but be careful: when returning a value, you must omit the; (semi-colon) after the last expression in the if or else block (see section Expressions in Chapter 2, Using Variables and Types). Moreover, all branches always must return a value of the same type.

This also alleviates the need for a ternary operator (?: ), like in C++; simply use if, as follows:

let adult = true; 
let age = if adult { "+18" } else { "-18" }; 
println!("Age is {}", age);  // 

This gives the following output:

    Age is +18
Exercise:
  1. See code in Chapter 3/exercises/iftest.rs.
  2. Try adding a; (semi-colon) after the +18 and -18 values, like this {"+18";}, what value will be printed for the variable age? What happens if you type annotate the variable age as &str?
  3. See if you can omit the { } (curly braces) if there is only one statement in the block.
  4. Also, verify if this code is OK:
    let health = -3;
    let result = if health <=0 { "Game over man!" };

How would you correct this statement if necessary?--by using pattern matching, which we will examine in the next chapter, also branches code, but does so based on the value of a variable.

主站蜘蛛池模板: 泉州市| 磴口县| 西贡区| 彩票| 景谷| 防城港市| 山东省| 阜城县| 荔波县| 肥城市| 隆化县| 佛冈县| 青冈县| 江安县| 桦甸市| 田林县| 安图县| 大冶市| 盐城市| 丹棱县| 杭锦后旗| 乐山市| 都兰县| 宜丰县| 西林县| 蓝田县| 紫阳县| 色达县| 长岛县| 日照市| 乌兰察布市| 涪陵区| 西林县| 麟游县| 湛江市| 九江县| 盘山县| 措美县| 剑河县| 巴彦县| 拉萨市|