English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Rust Loops

Rust hat neben flexiblen bedingten Anweisungen auch reife Schleifenstrukturen. Dies sollte erfahrene Entwickler sofort auffallen.

While-Schleife

While-Schleifen sind die typischsten bedingten bedingten Schleifen:

fn main() {
    let mut number = 1; 
    while number != 4  
        println!("{}", number); 
        number += 1; 
    } 
    println!("EXIT"); 
}

Running Result:

1
2
3
EXIT

Bis zum Datum der Erstellung dieses Handbuchs hat die Sprache Rust noch kein do-Die Verwendung von while, aber do wird als Reservewort festgelegt, möglicherweise wird es in zukünftigen Versionen verwendet.

In der C-Sprache wird der For-Schleife mit einem ternären Ausdruck gesteuert, aber in Rust gibt es diese Verwendung nicht, sie muss durch eine while-Schleife ersetzt werden:

C-Sprache

int i; 
for(i = 0; i < 10; i++) { 
    // Schleifenkörper
}

Rust

let mut i = 0; 
while i < 10  
    // Schleifenkörper 
    i += 1; 
}

For-Schleife

For-Schleifen sind die häufigsten Schleifenstrukturen und werden oft verwendet, um lineare Datenstrukturen (z.B. Arrays) zu durchlaufen. For-Schleifen durchlaufen Arrays:

fn main() { 
    10 2 3 4 5 
    for i in a.iter() { 
        println!("Wert ist: {}", i); 
    } 
}

Running Result:

Wert ist: 10
Wert ist: 20
Wert ist: 30
Wert ist: 40
Wert ist: 50

fn main() { 
10 2 3 4 5 
    5  
        println!("a[{}] = {} 
    } 
}

Running Result:

a[0] = 10
a[1] = 20
a[2] = 30
a[3] = 40
a[4] = 50

loop loop

Experienced developers have certainly encountered several situations where a loop cannot determine whether to continue the loop at the beginning and end, and must control the loop within the loop body. If such a situation occurs, we often implement the operation of exiting the loop in the middle of a while (true) loop body.

Rust has a native infinite loop structure called loop:

fn main() { 
    let s = ['R', 'U', 'N', 'O', 'O', 'B']; 
    let mut i = 0; 
    loop { 
        let ch = s[i]; 
        if ch == 'O' { 
            break; 
        } 
        println!("'{}'", ch);
        i += 1; 
    } 
}

Running Result:

'R' 
'U' 
'N'

The loop loop can exit the entire loop and return a value to the outside, similar to return, by using the break keyword. This is a very clever design, because loops like loop are often used as search tools. If something is found, of course, the result should be handed over:

fn main() { 
    let s = ['R', 'U', 'N', 'O', 'O', 'B']; 
    let mut i = 0; 
    let location = loop { 
        let ch = s[i];
        if ch == 'O' { 
            break i; 
        } 
        i += 1; 
    }; 
    println!("The index of 'O' is {}", location); 
}

Running Result:

 The index of 'O' is 3