How to create an infinite loop in Rust

3 Answers

0 votes
fn main() {
    let mut count = 0u16;
 
    loop { // infinite loop
        count += 1;
 
        if count == 4 {
            println!("count == 4");
            continue;
        }
 
        println!("{}", count);
 
        if count == 7 {
            println!("count == 7 -> break");
            break;
        }
    }
}

 
 
/*
run:
 
1
2
3
count == 4
5
6
7
count == 7 -> break
 
*/

 



answered May 4, 2023 by avibootz
edited Apr 10 by avibootz
0 votes
fn main() {
    let mut count = 0u16;
 
    while true { // infinite loop
        count += 1;
 
        if count == 4 {
            println!("count == 4");
            continue;
        }
 
        println!("{}", count);
 
        if count == 7 {
            println!("count == 7 -> break");
            break;
        }
    }
}

 
/*
run:
 
1
2
3
count == 4
5
6
7
count == 7 -> break
 
*/

 



answered Apr 10 by avibootz
0 votes
fn main() {
    let mut i = 0;
    let mut count = 0u16;
 
    // Infinite loop with a condition that never changes
    while i >= 0 {
        println!("i = {}", i);
        i += 1;
        
        count += 1;
 
        if count == 4 {
            println!("count == 4");
            continue;
        }
 
        println!("{}", count);
 
        if count == 7 {
            println!("count == 7 -> break");
            break;
        }
    }
}

 
/*
run:
 
i = 0
1
i = 1
2
i = 2
3
i = 3
count == 4
i = 4
5
i = 5
6
i = 6
7
count == 7 -> break
 
*/

 



answered Apr 10 by avibootz
...