Ben Chuanlong Du's Blog

It is never too late to learn.

Loop in Rust

In [ ]:
:timing
:sccache 1

loop

In [12]:
let mut count = 0;
loop {
    println!("{}", count);
    count += 1;
    if count >= 5 {
        break;
    }
}
0
1
2
3
4
Out[12]:
()

while loop

In [10]:
let mut count = 0;
while count < 5 {
    println!("{}", count);
    count += 1;
}
0
1
2
3
4
Out[10]:
()
In [11]:
let mut count = 0;
while true {
    println!("{}", count);
    count += 1;
    if count >= 5 {
        break;
    }
}
0
1
2
3
4
Out[11]:
()

for loop

In [6]:
for word in "how are you".split_whitespace() {
    println!("{}", word);
}
how
are
you
Out[6]:
()
In [5]:
for i in 1..5 {
    println!("{}", i);
}
1
2
3
4
Out[5]:
()
In [4]:
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}
In [4]:
let names: Vec<&str> = vec!["Pascal", "Elvira", "Dominic", "Christoph"];

for name in names {
    println!("{}", name);
}
Pascal
Elvira
Dominic
Christoph
Out[4]:
()
In [6]:
let names = vec!["Pascal", "Elvira", "Dominic", "Christoph"];

for name in &names {
    println!("{}", name);
    print_type_of(name);
}
Pascal
&str
Elvira
&str
Dominic
&str
Christoph
&str
Out[6]:
()

Comments