【Rust】Rust ~ 制御文 ~

◾️はじめに

Rustの基本として「繰り返し」と「条件分岐」を扱う

# これで一通り基本は終わった、、、

目次

【1】繰り返し
 1)for in
 2)while
 3)loop
【2】条件分岐
 1)if/else if/else
 2)三項演算子
 3)match

【1】繰り返し

1)for in

* 基本は、for in構文でイテレータでループさせる

https://doc.rust-jp.rs/rust-by-example-ja/flow_control/for.html

for n in 1..=10 {
    println!("{}", n);
}

let names = vec!["Bob", "Frank", "Ferris"];
for name in names.into_iter() {
    println!("{}", name);
}

2)while

* 普通のプログラムと同じ

https://doc.rust-jp.rs/rust-by-example-ja/flow_control/while.html

let mut count = 0;
while count < 10 {
    count += 1;
    println!("{}", count);
}

3)loop

* 無限ループするために使用
 => 訳注: while Trueと同じだが、ループのたびに条件を確認しないため、
  若干高速になる。

https://doc.rust-jp.rs/rust-by-example-ja/flow_control/loop.html

let mut count = 0;
loop {
    count += 1;
    println!("{}", count);

    if count == 5 {
        println!("OK, that's enough");
        // Exit this loop
        break;
    }
}

【2】条件分岐

* Scala ができれば、普通にできる

1)if/else if/else

* ここは普通のプログラムと変わらん

https://doc.rust-jp.rs/rust-by-example-ja/flow_control/if_else.html

let n = 5;
if n < 0 {
    print!("{} is negative", n);
} else if n > 0 {
    print!("{} is positive", n);
} else {
    print!("{} is zero", n);
}

2)三項演算子

* 普通にif/else文できる

https://doc.rust-jp.rs/rust-by-example-ja/flow_control/if_else.html

let result = if n % 2 == 0 { "even number" } else { "odd number" };

3)match

* これもScalaやってればほぼ同じ

https://doc.rust-jp.rs/rust-by-example-ja/flow_control/match.html

let number = 13;
match number {
    1 => println!("One!"),
    2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
    13..=19 => println!("A teen"),
    _ => println!("Ain't special"),
}

let boolean = true;
let binary = match boolean {
    false => 0,
    true => 1,
};

関連記事

Rust ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/04/22/234808
Rust ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2025/11/26/224648
Rust ~ 変数 / データ型 ~
https://dk521123.hatenablog.com/entry/2025/12/05/000647