Inhalt der Lektion

Eine Summe Schritt für Schritt bilden

Starte bei null und zähle jede Zahl der Reihe nach zur bisherigen Summe dazu.

Ein einfaches Beispiel

Am Anfang2 + 4
Ergebnis6
main.rs
fn main() {
    let mut total: i64 = 0;
    total += 2;
    total += 4;
    println!("{}", total);
}
Ausgabe
6
Anzeigen

Beispiele aus dem Alltag

Drei Klassen spenden 5, 2 und 4 Bücher. Wie viele Bücher kann die Bibliothek auf ihre Regale stellen?

Am Anfang5 + 2 + 4
Ergebnis11
main.rs
fn main() {
    let books: [i64; 3] = [5, 2, 4];
    let mut total: i64 = 0;
    let mut i: i64 = 0;
    while i < 3 {
        total += books[(i) as usize];
        i += 1;
    }
    println!("{}", total);
}
Ausgabe
11
Beispiel ausführen
Terminal
rustc main.rs
./main
Offizielle Dokumentation