rust 條件語句和迴圈的用法 7

2021-10-25 14:20:47 字數 3017 閱讀 6542

目錄

一,條件語句

二,迴圈

(一)loop,while , for 三種迴圈 ,三個返回關鍵字 continue , break , return

(二)for動態修改陣列的值

(三)得到陣列的下標

(四)跳出多重迴圈

//1.第一種用法  if  else

let flag = true;

if flag else

//2.第二種用法 if else if else

let num = 3;

if num==1 else if flag && num ==2 else

//3.第三種用法 if可以具有返回值,多個分支中的返回值型別必須一致

let num = if flag else ;

println!("",num);

管這叫匹配,不過我真心覺得這貨是swith

let x = 5;

match x

// if let 表示式的缺點在於其窮盡性沒有為編譯器所檢查,而 match 表示式則檢查了。

// 如果去掉最後的 else 塊而遺漏處理一些情況,編譯器也不會警告這類可能的邏輯錯誤。

let mut num ;

let color: option<&str> = none;

if let some(cl) = color else if 1==1 else

//返回值不加 ;

let bool1 = true;

let num = if bool1 else ;

// while let 條件迴圈

let mut list = vec::new();

list.push(1);

list.push(2);

while let some(top) = list.pop() ", top);

}

fn main() 

fn loop_f()",num);

continue;

}else if num == 3

};println!("loop_f num= {} , m = {}",num, m);

}fn while_f()",num)

}}fn for_f()

println!("for_f num = {}", num );

}//或者這樣,給出乙個含有這之間值得迭代器。當然它不包括上限值array.len(), 0,1...array.len()-1

for num in 0..array.len()

println!("for_f num = {}", num );

}}

let mut array = [6,7,8];

for num in 0..array.len()

println!("for_f num = ", array );

console:

for_f num = [7, 8, 9]

//我們需要知道當前元素的下標,這樣顯然比較費勁,rust 提供了enumerate 函式

let mut array = [6,7,8];

let mut j = 0;

for i in array.iter() and j = {}", i, j);

j=j+1;

}println!("array enumerate");

for (i, &j) in array.iter().enumerate() and j = {}", i, j);

}println!("() enumerate");

for (i,j) in (5..7).enumerate() and j = {}", i, j);

}console:

i = 6 and j = 0

i = 7 and j = 1

i = 8 and j = 2

array enumerate

i = 0 and j = 6

i = 1 and j = 7

i = 2 and j = 8

() enumerate

i = 0 and j = 5

i = 1 and j = 6

邏輯和使用迴圈標籤(loop labels)

使用迴圈標籤 continue  相當於 break, break相當於 return。不過標籤在特殊情況下更靈活

fn one()",x);

for y in 0..4 , y: {}", x, y);

continue 'outer;}}

}}fn two()",x);

for y in 0..4 , y: {}", x, y);

break ;}}

}}fn three()",x);

for y in 0..4 , y: {}", x, y);

return ;}}

}}fn four()",x);

for y in 0..4 , y: {}", x, y);

break 'outer;}}

}}console:

one x: 0

one x: 1

one x: 2

one x: 2, y: 2

one x: 3

two x: 0

two x: 1

two x: 2

two x: 2, y: 2

two x: 3

three x: 0

three x: 1

three x: 2

three x: 2, y: 2

four x: 0

four x: 1

four x: 2

four x: 2, y: 2

條件語句和迴圈語句

條件語句 if語句有三種用法 1.if 表示式 如果表示式的值為真,則執行括號內的復合語句 2.if 表示式 else 如果表示式的值為真,則執行語句1,否則執行語句2 3.if 表示式 else if else if else 如果表示式的值為真,則執行對應的語句然後跳出if語句執行後面的語句,若...

條件和迴圈語句

python條件語句是通過一條或多條語句的執行結果 true或者false 來決定執行的 塊。if 判斷條件 執行語句 else 執行語句 開始有縮排的概念 基本判斷語句 age 12 if age 18 print 18歲以下不宜 if語句後面必須有 自動縮排 if語句寫完後,要退回原有縮排繼續寫...

Python 的條件語句和迴圈語句

一 順序結構 順序結構是最簡單的一種程式結構,程式按照語句的書寫次序自上而下順序執行。二 分支控制語句 python條件語句是通過一條或多條語句的執行結果 true或者false 來決定執行的 塊。python中if語句的一般形式如下所示 if condition 1 statement block...