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

? Operator का उपयोग

? mark एक shortcut है जो कहता है "अगर यह fail हो गया, यहां रुको और failure मुझे call करने वाले को सौंप दो।"
Syntax
rust
fn name() -> Result<T, E> {
    let value = fallible()?;
    Ok(value)
}

Basic Use of the ? Operator

किसी Result return करने वाले expression के बाद ? रखना अपने आप Ok value unwrap करता है, या अगर यह fail हुआ तो तुरंत enclosing function से Err return करता है।

उदाहरण: Basic Use of the ? Operator

markup
// Define the function `parse_number` taking `s` and returning a `Result<i32, std::num::ParseIntError>`
fn parse_number(s: &str) -> Result<i32, std::num::ParseIntError> {
    // Declare an immutable variable `n`, set to `s.parse::<i32>()?`
    let n = s.parse::<i32>()?;
    Ok(n * 2)
}

// Entry point: execution of the program starts here
fn main() {
    // Match on `parse_number("21")` and branch by pattern
    match parse_number("21") {
        Ok(v) => println!("Doubled: {}", v),
        Err(e) => println!("Error: {:?}", e),
    }
}

Chaining Multiple Fallible Calls

? operator कई fallible operations chain करते समय चमकता है, हर step को तुरंत अपनी error propagate करने देते हुए बजाय हर call के लिए एक nested match ज़रूरी बनाने के।

उदाहरण: Chaining Multiple Fallible Calls

markup
// Define the function `parse_and_add` taking `a`, `b` and returning a `Result<i32, std::num::ParseIntError>`
fn parse_and_add(a: &str, b: &str) -> Result<i32, std::num::ParseIntError> {
    // Declare an immutable variable `x`, set to `a.parse::<i32>()?`
    let x = a.parse::<i32>()?;
    // Declare an immutable variable `y`, set to `b.parse::<i32>()?`
    let y = b.parse::<i32>()?;
    Ok(x + y)
}

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

The Enclosing Function Must Return a Compatible Type

? सिर्फ उस function के अंदर उपयोग किया जा सकता है जिसका return type खुद एक compatible error type वाला Result (या Option) हो, क्योंकि इसे propagated error return करने के लिए कहीं चाहिए।

उदाहरण: The Enclosing Function Must Return a Compatible Type

markup
// Define the function `compute` taking `input` and returning a `Result<i32, std::num::ParseIntError>`
fn compute(input: &str) -> Result<i32, std::num::ParseIntError> {
    // Declare an immutable variable `value` (an integer), set to `input.parse()?`
    let value: i32 = input.parse()?;
    Ok(value + 100)
}

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

Using ? with Option

? operator Option पर भी काम करता है, अगर value None हो तो function से जल्दी None return करते हुए, Result के साथ यह कैसे काम करता है उसे mirror करते हुए।

उदाहरण: Using ? with Option

markup
// Define the function `first_char_uppercase` taking `s` and returning a `Option<char>`
fn first_char_uppercase(s: &str) -> Option<char> {
    // Declare an immutable variable `c`, set to `s.chars().next()?`
    let c = s.chars().next()?;
    Some(c.to_ascii_uppercase())
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{:?}" to the console, substituting in `first_char_uppercase("rust")` (with a trailing newline)
    println!("{:?}", first_char_uppercase("rust"));
    // Print "{:?}" to the console, substituting in `first_char_uppercase("")` (with a trailing newline)
    println!("{:?}", first_char_uppercase(""));
}
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 के अंदर ? उपयोग करना जिसका return type Result (या Option) नहीं, जो compile होने में fail होता है।
  2. यह भूल जाना कि ? सिर्फ error propagate करता है -- यह खुद कुछ print नहीं करता या program crash नहीं करता।
  3. बिना conversion के कई ? calls में incompatible error types mix करना, जिसे compiler reject करेगा जब तक types unify न हों।
चैप्टर सारांश
  • किसी Result-returning expression के बाद ? Ok values unwrap करता है या Err के साथ जल्दी return करता है।
  • Enclosing function को ? उपयोग होने के लिए खुद एक compatible Result (या Option) type return करना चाहिए।
  • ? हर fallible call को manually match करने की तुलना में boilerplate को नाटकीय रूप से घटाता है।
  • ? Option के साथ भी उपयोग किया जा सकता है, अगर value None हो तो जल्दी None return करते हुए।
🔒

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.