← Back to Rust Course | Chapter 10: Error Handling | Lesson 1 of 6

Result Type का उपयोग

Result यह कहने का Rust का तरीका है कि कोई operation या तो काम कर गया और आपको एक answer देता है, या fail हो गया और बताता है क्यों।
Syntax
rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}

match result {
    Ok(value) => expression,
    Err(e) => expression,
}

What Is Result

Result<T, E> दो variants वाला एक enum है: Ok(value) success के लिए जो एक T रखता है, और Err(error) failure के लिए जो एक E रखता है। यह standard तरीका है जिससे Rust fallible operations represent करता है।

उदाहरण: What Is Result

markup
// Define the function `divide` taking `a`, `b` and returning a `Result<f64, String>`
fn divide(a: f64, b: f64) -> Result<f64, String> {
    // Check whether `b == 0.0`
    if b == 0.0 {
        Err(String::from("division by zero"))
    // Otherwise, run this branch
    } else {
        Ok(a / b)
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{:?}" to the console, substituting in `divide(10.0, 2.0)` (with a trailing newline)
    println!("{:?}", divide(10.0, 2.0));
}

Matching on Result

match आपको किसी Result के success और failure दोनों cases explicitly handle करने देता है, ज़रूरत के अनुसार value या error निकालते हुए।

उदाहरण: Matching on Result

markup
// Define the function `divide` taking `a`, `b` and returning a `Result<f64, String>`
fn divide(a: f64, b: f64) -> Result<f64, String> {
    // Check whether `b == 0.0`
    if b == 0.0 {
        Err(String::from("division by zero"))
    // Otherwise, run this branch
    } else {
        Ok(a / b)
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Match on `divide(5.0, 0.0)` and branch by pattern
    match divide(5.0, 0.0) {
        Ok(value) => println!("Result: {}", value),
        Err(e) => println!("Error: {}", e),
    }
}

Parsing Returns a Result

कई standard library operations जो fail हो सकते हैं, जैसे किसी string को एक number में parse करना, एक Result return करते हैं ताकि caller को तय करना पड़े कि एक malformed input कैसे handle करना है।

उदाहरण: Parsing Returns a Result

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `input`, set to `"42"`
    let input = "42";
    // Declare an immutable variable `parsed` (a `Result<i32, _>`), set to `input.parse()`
    let parsed: Result<i32, _> = input.parse();
    // Match on `parsed` and branch by pattern
    match parsed {
        Ok(n) => println!("Parsed number: {}", n),
        Err(_) => println!("Could not parse"),
    }
}

Result vs Option

Option signal करता है कि कोई value बिल्कुल मौजूद है या नहीं, जबकि Result अतिरिक्त रूप से इसकी जानकारी रखता है कि कोई operation क्यों fail हुआ, इसे बेहतर choice बनाते हुए जब भी failure का reason मायने रखता हो।

उदाहरण: Result vs Option

markup
// Define the function `safe_divide` taking `a`, `b` and returning a `Result<i32, String>`
fn safe_divide(a: i32, b: i32) -> Result<i32, String> {
    // Check whether `b == 0`
    if b == 0 {
        Err(String::from("cannot divide by zero"))
    // Otherwise, run this branch
    } else {
        Ok(a / b)
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{:?}" to the console, substituting in `safe_divide(10, 2)` (with a trailing newline)
    println!("{:?}", safe_divide(10, 2));
    // Print "{:?}" to the console, substituting in `safe_divide(10, 0)` (with a trailing newline)
    println!("{:?}", safe_divide(10, 0));
}
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. किसी function से returned Result को नज़रअंदाज़ करना -- compiler एक unused Result के बारे में warn करता है क्योंकि errors चुपचाप drop हो सकती थीं।
  2. यह मान लेना कि Result और Option interchangeable हैं -- Result error information रखता है, जबकि Option बस absence signal करता है।
  3. Result को पहले match या unwrap किए बिना सीधे Ok value उपयोग करने की कोशिश करना।
चैप्टर सारांश
  • Result<T, E> या तो success (Ok(value)) या failure (Err(error)) represent करता है।
  • वे functions जो fail हो सकते हैं, जैसे parsing या file I/O, आमतौर पर सीधे panic करने के बजाय एक Result return करते हैं।
  • किसी Result के Ok और Err दोनों cases handle करने का सबसे explicit तरीका match है।
  • Rust का compiler warn करता है जब एक Result unused छोड़ दिया जाता है, आपको potential errors handle करने की ओर धकेलते हुए।
🔒

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.