← Back to Rust Course | Chapter 9: Collections | Lesson 5 of 6

Collections को Iterate करना

Iterating का मतलब है किसी list में हर item को देखने या उपयोग करने के लिए एक-एक करके visit करना।
Syntax
rust
for item in &collection {}       // borrow
for item in &mut collection {}   // mutably borrow
for item in collection {}        // consume
for (i, item) in collection.iter().enumerate() {}

Iterating by Reference with iter

.iter() हर element के references का एक iterator produce करता है, original collection को untouched और बाद में अब भी usable छोड़ते हुए।

उदाहरण: Iterating by Reference with iter

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `vec![1, 2, 3]`
    let numbers = vec![1, 2, 3];
    // Loop over `numbers.iter()`, binding each item to `n`
    for n in numbers.iter() {
        // Print "Value: {}" to the console, substituting in `n` (with a trailing newline)
        println!("Value: {}", n);
    }
    // Print "Still usable: {:?}" to the console, substituting in `numbers` (with a trailing newline)
    println!("Still usable: {:?}", numbers);
}

Mutating in Place with iter_mut

.iter_mut() हर element के mutable references produce करता है, आपको iteration के दौरान collection की contents सीधे modify करने देते हुए।

उदाहरण: Mutating in Place with iter_mut

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `numbers`, initialized to `vec![1, 2, 3]`
    let mut numbers = vec![1, 2, 3];
    // Loop over `numbers.iter_mut()`, binding each item to `n`
    for n in numbers.iter_mut() {
        *n *= 10;
    }
    // Print "{:?}" to the console, substituting in `numbers` (with a trailing newline)
    println!("{:?}", numbers);
}

Taking Ownership with into_iter

किसी collection को value से iterate करना (into_iter() के साथ, या एक plain for x in collection) collection को consume करता है, हर element को एक समय में एक बाहर move करते हुए।

उदाहरण: Taking Ownership with into_iter

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `words`, set to `vec![String::from("a"), String::from("b")]`
    let words = vec![String::from("a"), String::from("b")];
    // Loop over `words.into_iter()`, binding each item to `word`
    for word in words.into_iter() {
        // Print "Owned word: {}" to the console, substituting in `word` (with a trailing newline)
        println!("Owned word: {}", word);
    }
}

Chaining Iterator Adapters

.map() और .filter() जैसे iterator methods को आखिर में results को collect या sum करने से पहले declaratively elements transform और select करने के लिए एक साथ chain किया जा सकता है।

उदाहरण: Chaining Iterator Adapters

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `vec![1, 2, 3, 4, 5]`
    let numbers = vec![1, 2, 3, 4, 5];
    // Declare an immutable variable `sum_of_squares` (an integer), set to `numbers.iter().map(|n| n * n).filter(|n| n % 2 == 0).sum()`
    let sum_of_squares: i32 = numbers.iter().map(|n| n * n).filter(|n| n % 2 == 0).sum();
    // Print "Sum of even squares: {}" to the console, substituting in `sum_of_squares` (with a trailing newline)
    println!("Sum of even squares: {}", sum_of_squares);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. for item in collection (ownership लेते हुए) उपयोग करना जब आपका मतलब सिर्फ items पढ़ना था, इसके बजाय .iter() चाहिए।
  2. यह भूल जाना कि .iter_mut() iteration के दौरान किसी collection के हर element को जगह पर modify करने के लिए मौजूद है।
  3. यह मान लेना कि किसी Vec<T> पर .iter() सीधे T values yield करता है, जब यह असल में &T references yield करता है।
चैप्टर सारांश
  • .iter() collection की ownership लिए बिना हर element के immutable references yield करता है।
  • .iter_mut() mutable references yield करता है, आपको iteration के दौरान elements को जगह पर modify करने देते हुए।
  • into_iter() (या एक bare for x in collection) collection और इसके elements की ownership लेता है।
  • .map(), .filter(), और .sum() जैसे iterator adapters को collections को declaratively process करने के लिए एक साथ chain किया जा सकता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.