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語句出現在另一個ifelse塊的主體內時，它稱為巢狀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