Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ループから戻る

loop の用途の 1 つは、操作が成功するまで再試行することです。ただし、その操作が値を返す場合は、その値を残りのコードに渡す必要があるかもしれません。その値を break の後に置けば、loop 式から返されます。

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    assert_eq!(result, 20);
}