# Rust if語句

`if`語句確定條件是否為真。如果條件為`true`，則執行`if`塊，否則，控制會跳過`if`塊。

• if塊
• if-else塊
• if else-if階梯塊
• 巢狀if語句

## if語句

`if`語句塊的語法 -

``````if condition
{
//block statements;
}
``````

`if`語句的流程圖 -

``````fn main(){

let a=1;
if a==1
{
println!("a is equal to 1");
}
}
``````

``````a is equal to 1
``````

## if-else語句

if-else語句的語法

``````if condition
{
//block statements
}else{
//block statements
}
``````

if-else的流程圖

``````fn main()
{
let a=3;
let b=4;
if a>b
{
println!("a is greater than b");
}
else
{
println!("a is smaller than b");
}
}
``````

``````a is smaller than b
``````

## else-if語句

`else-if`語句的語法 -

``````if condition 1
{
//block statements
}else if condition 2
{
//block statements
}
.
.
else{
//block statements
}
``````

`else if`語句塊的流程圖 -

``````fn main(){

let num= -5;
if num>0
{
println!("number is greater than 0");
}
else if num<0
{
println!("number is less than 0 ");
}
else
{
println!("number is not equal to 0");
}
}
``````

``````number is less than 0
``````

## 巢狀if-else語句

`if-else`語句出現在另一個`if``else`塊的主體內時，它稱為巢狀`if-else`

``````if condition 1
{
// 巢狀if/else塊
if condition 2
{
//block statements
}else
{
//block statements
}
}else{
//block statements
}
``````

``````fn main(){

let a=5;
let b=6;
if a!=b
{
if a>b
{
println!("a is greater than b");
}else{
println!("a is less than b");
}
}

else
{
println!("a is equal to b");
}
}
``````

``````a is less than b
``````