Rustでループを使おう

Rust_1636986325.webp
目次

はじめに

Rustには3種類のループ構文があるようです。 一般的によく見かけるforとWhileに加えてloopがありますのでそれぞれ動かしてみましょう。

loop

loopの特徴は、抜け出すときに値を渡せるところです。 breakに戻り値を指定してループを抜け出すことができます。

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

        if count == 10 {
            break count;
        }
    };
    println!("{}", result)
}

実行結果

count:0
count:1
count:2
count:3
count:4
count:5
count:6
count:7
count:8
count:9
10

while

条件を指定してループ処理を行うときに使うのがこちら

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

実行結果

count:0
count:1
count:2
count:3
count:4
count:5
count:6
count:7
count:8
count:9
count:10

for

大本命のfor文。繰り返したい回数や、配列やVectorの要素の数分だけで繰り返すことが出来ます。

fn main() {
    for i in 0..10 {
        println!("i:{}", i);
    }

    let count_num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    for elem in count_num {
        println!("elem:{}", elem);
    }
}

実行結果

i:0
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9
elem:0
elem:1
elem:2
elem:3
elem:4
elem:5
elem:6
elem:7
elem:8
elem:9
elem:10

まとめ

今日はこんなところでしょうか。

Related Post

> Rustでループを使おう
RustのIteratorを使って繰り返し処理を実行して理解しよう
> Rustでループを使おう
モダン言語Rustを勉強してみよう(基本構文)
> Rustでループを使おう
Rustを始める - WSLとVisual Studio Codeでの開発環境構築

おすすめの商品

>