Rust学习笔记 2.2 控制流(control flow)

205 阅读1分钟

2.2 控制流(control flow)

Execution Flow

语句

 if
 else if
 else

循环

loopingiteration

关键字:

  • loop无尽的循环
  • while有条件的循环
  • for
  • break
  • continue

loop and while

因为loop是无尽的循环,所以需要通过break退出:

image-20220707170928433

for

 fn main() {
     for 元素 in 集合 {
       // 使用元素
     }
 }
使用方法等价使用方式所有权
for item in collectionfor item in IntoIterator::into_iter(collection)转移所有权
for item in &collectionfor item in collection.iter()不可变借用
for item in &mut collectionfor item in collection.iter_mut()可变借用

Match

if...else类似,但是必须写出所有条件下的执行代码

if...else不同的是:

  • match会在编译时检查错误
  • if...else则不会,只会在运行时报错
 use rand::Rng;
 ​
 fn main() {
     let mut rng = rand::thread_rng();
     let num = rng.gen_range(0..10);
     match num {
         1 => println!("first"),
         2 => println!("second"),
         3 => println!("third"),
         _ => println!("other"),
     }
 }
 ​

可以用下划线_表示其它所有情况

tips:在 Rust 中 _ 的含义是忽略该值或者类型的意思,如果不使用 _,那么编译器会给你一个 变量未使用的 的警告。