Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use .iter() in a for loop | Rust [duplicate]

Tags:

rust

In these two examples is there any benefit in using .iter() in a for loop?

let chars = ['g', 'd', 'k', 'k', 'n'];

for i in chars {
    println!("{}", i);
}

let chars = ['g', 'd', 'k', 'k', 'n'];

for i in chars.iter() {
    println!("{}", i);
}
like image 408
Kuly14 Avatar asked Apr 13 '26 19:04

Kuly14


1 Answers

for i in array is interpreted by the compiler as for i in array.into_iter().

This means that you are iterating over elements of type char, and the array is copied (as an array is Copy if its elements are also Copy).

On the other hand, for i in array.iter() references the array instead iterates over elements of type &char, avoiding a copy.

like image 123
SirDarius Avatar answered Apr 15 '26 10:04

SirDarius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!