? Operator का उपयोग
? mark एक shortcut है जो कहता है "अगर यह fail हो गया, यहां रुको और failure मुझे call करने वाले को सौंप दो।"In this page:
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
// 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),
}
}
Login to try C/C++/Java/PHP code in the editor
Chaining Multiple Fallible Calls
? operator कई fallible operations chain करते समय चमकता है, हर step को तुरंत अपनी error propagate करने देते हुए बजाय हर call के लिए एक nested match ज़रूरी बनाने के।
उदाहरण: Chaining Multiple Fallible Calls
// 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"));
}
Login to try C/C++/Java/PHP code in the editor
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
// 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"));
}
Login to try C/C++/Java/PHP code in the editor
Using ? with Option
? operator Option पर भी काम करता है, अगर value None हो तो function से जल्दी None return करते हुए, Result के साथ यह कैसे काम करता है उसे mirror करते हुए।
उदाहरण: Using ? with Option
// 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(""));
}
Login to try C/C++/Java/PHP code in the editor
- किसी ऐसे function के अंदर
?उपयोग करना जिसका return typeResult(याOption) नहीं, जो compile होने में fail होता है। - यह भूल जाना कि
?सिर्फ error propagate करता है -- यह खुद कुछ print नहीं करता या program crash नहीं करता। - बिना conversion के कई
?calls में incompatible error types mix करना, जिसे compiler reject करेगा जब तक types unify न हों।
- किसी
Result-returning expression के बाद?Okvalues unwrap करता है याErrके साथ जल्दी return करता है। - Enclosing function को
?उपयोग होने के लिए खुद एक compatibleResult(याOption) type return करना चाहिए। ?हर fallible call को manually match करने की तुलना में boilerplate को नाटकीय रूप से घटाता है।?Optionके साथ भी उपयोग किया जा सकता है, अगर valueNoneहो तो जल्दीNonereturn करते हुए।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: