← Back to Rust Course | Chapter 8: Enums & Pattern Matching | Lesson 5 of 7

while let का Syntax

while let तब तक एक action दोहराता रहता है जब तक एक value आपके चाहे pattern से match करती रहे।
Syntax
rust
while let Pattern(binding) = expression {
    // body
}

Basic while let

while let अपना block तब तक दोहराता है जब तक दिया pattern value से match करता रहे, हर iteration की शुरुआत में फिर से जांचा गया।

उदाहरण: Basic while let

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `stack`, initialized to `vec![1, 2, 3]`
    let mut stack = vec![1, 2, 3];
    // Keep looping while `let Some(top) = stack.pop()` holds
    while let Some(top) = stack.pop() {
        // Print "Popped: {}" to the console, substituting in `top` (with a trailing newline)
        println!("Popped: {}", top);
    }
}

Draining a Queue-like Structure

while let खाली होने तक एक structure से बार-बार items निकालने के लिए विशेष रूप से उपयोगी है, क्योंकि कुछ न बचने पर .pop() naturally None return करता है।

उदाहरण: Draining a Queue-like Structure

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `queue`, initialized to `vec!["a", "b", "c"]`
    let mut queue = vec!["a", "b", "c"];
    // Keep looping while `let Some(item) = queue.pop()` holds
    while let Some(item) = queue.pop() {
        // Print "Processing: {}" to the console, substituting in `item` (with a trailing newline)
        println!("Processing: {}", item);
    }
    // Print "Queue is now empty" to the console (with a trailing newline)
    println!("Queue is now empty");
}

while let With a Custom Enum

while let किसी भी enum pattern के साथ काम करता है, सिर्फ Option के साथ नहीं, जब तक हर iteration pattern के खिलाफ test करने के लिए एक नई value produce करे।

उदाहरण: while let With a Custom Enum

markup
// Define an enum `Fetch` listing its possible variants
enum Fetch {
    Item(i32),
    Empty,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `values`, initialized to `vec![10, 20, 30]`
    let mut values = vec![10, 20, 30];
    // Declare a mutable variable `next`, initialized to `|| values.pop().map_or(Fetch::Empty, Fetch::Item)`
    let mut next = || values.pop().map_or(Fetch::Empty, Fetch::Item);
    // Keep looping while `let Fetch::Item(v) = next()` holds
    while let Fetch::Item(v) = next() {
        // Print "Got item: {}" to the console, substituting in `v` (with a trailing newline)
        println!("Got item: {}", v);
    }
}

Comparing to a Manual loop

while let के बिना, उसी logic को एक loop चाहिए जो एक match और None arm में एक explicit break के साथ combine किया गया हो -- while let इस आम pattern को कहीं ज़्यादा concisely express करता है।

उदाहरण: Comparing to a Manual loop

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `stack`, initialized to `vec![5, 10]`
    let mut stack = vec![5, 10];
    // Loop forever until an explicit `break`
    loop {
        // Match on `stack.pop()` and branch by pattern
        match stack.pop() {
            Some(v) => println!("value: {}", v),
            None => break,
        }
    }
}
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. यह भूल जाना कि pattern अब match न करने पर loop पहली बार में ही अपने आप रुक जाता है -- इसके लिए किसी manual break की ज़रूरत नहीं।
  2. किसी collection पर while let उपयोग करना जब एक plain for loop ज़्यादा simple और idiomatic होता।
  3. यह न समझना कि किसी Vec पर .pop() एक Option return करता है, जो बिल्कुल वही shape है जिसे consume करने के लिए while let Some(x) = ... design किया गया है।
चैप्टर सारांश
  • while let pattern = value { ... } तब तक loop करता है जब तक value दिए pattern से match करता रहे।
  • यह आमतौर पर Option return करने वाले methods के साथ जोड़ा जाता है, जैसे Vec::pop(), items को तब तक process करने के लिए जब तक कोई न बचे।
  • Match पहली बार fail होने पर loop अपने आप exit हो जाता है, उस case के लिए किसी explicit break की ज़रूरत नहीं।
  • while let अंदर एक match और break वाले manual loop की तुलना में boilerplate घटाता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.