yoklainterview sim

Backend Rs Error Handling Result Option Interview Questions

75 verified Backend Rs Error Handling Result Option interview questions — solve with answers, learn from explanations, test yourself in a real simulation.

Try the real simulation →

Sample questions

Rs Error Handling Result OptionDifficulty 1
fn save() -> Result<(), String> {
    Err("disk full".to_string())
}

fn main() {
    save();
    println!("done");
}

What happens when this is built and run with cargo run?
  • aCompilation stops: a Result returned by save() has to be matched or propagated with ?
  • bIt compiles, since an unused Result is only a warning, then prints done
  • cIt compiles cleanly and panics at runtime with the message disk full
  • dIt compiles cleanly and prints done; ignoring a Result is silent in Rust
Explanation:Result is marked #[must_use], so dropping one without inspecting it produces the warning unused Result that must be used. A warning is not an error: the binary builds, save() runs, its Err value is discarded, and done is printed. Nothing panics, because an Err value only panics if you call unwrap/expect on it.
Rs Error Handling Result OptionDifficulty 2
fn first(v: &[i32]) -> Result<i32, String> {
    let x = v.first()?;
    Ok(*x)
}

What does the compiler say about this function?
  • aIt compiles; ? on an Option inside a Result function converts None into Err(String::new())
  • bIt compiles; ? returns Err("None".to_string()) when the slice is empty
  • cIt fails with E0308 because v.first() returns Option<&i32> while x is used as i32
  • dIt fails with E0277: ? cannot be used on an Option in a function that returns Result
Explanation:The ? operator is tied to the return type of the enclosing function. In a function returning Result, ? accepts only Result values; applying it to v.first() (an Option<&i32>) yields E0277 with the message "the ? operator can only be used on Results, not Options, in a function that returns Result". The fix is v.first().ok_or_else(|| "empty".to_string())?. Rust never invents an error value from None.
Rs Error Handling Result OptionDifficulty 1
fn main() {
    let n: i32 = "1".parse()?;
    println!("{}", n);
}

Why does this not compile?
  • a? needs the enclosing function to return Result or Option, but this main returns ()
  • b? cannot be applied to parse(): its error type is not Box<dyn Error>
  • c? is not allowed in main; only functions called from main may use it
  • d? requires an explicit type annotation such as parse::<i32>() to pick the error type
Explanation:The error is E0277: "the ? operator can only be used in a function that returns Result or Option". ? desugars to an early return Err(From::from(e)), which is impossible when the function returns (). Changing the signature to fn main() -> Result<(), Box<dyn std::error::Error>> and ending with Ok(()) makes it compile. main is allowed to use ?, and the let n: i32 annotation already fixes the parse target.
Rs Error Handling Result OptionDifficulty 2
fn main() {
    let cfg: Option<&str> = None;
    let v = cfg.unwrap();
    println!("{}", v);
}

What is observed at runtime?
  • aThe program prints an empty line: unwrap on None yields the type's default value
  • bIt exits with code 1 after writing Error: None to stderr
  • cThe thread panics with called Option::unwrap() on a None value and the process exits with code 101
  • dCompilation fails: unwrap on an Option whose state is unknown is rejected
Explanation:Option::unwrap returns the inner value for Some and panics for None with exactly the message called Option::unwrap() on a None value. An uncaught panic in the main thread terminates the process with exit status 101. The compiler does not track whether the value is None; defaults come only from unwrap_or_default, and the Error: ... line with status 1 is what main returning Err produces, not a panic.
Rs Error Handling Result OptionDifficulty 2
fn main() {
    let r: Result<i32, String> = Err("disk full".to_string());
    let v = r.expect("reading config");
    println!("{}", v);
}

Which panic message does this produce?
  • areading config
  • bcalled Result::unwrap() on an Err value: "disk full"
  • creading config: "disk full"
  • ddisk full: reading config
Explanation:Result::expect(msg) panics with the custom message followed by a colon and the Debug rendering of the error: reading config: "disk full". The quotes come from String's Debug output. Plain unwrap() would instead print called Result::unwrap() on an Err value: "disk full". The custom text always comes first, and it is never dropped.
Rs Error Handling Result OptionDifficulty 2
fn parse(s: &str) -> Result<i32, String> {
    s.parse::<i32>().map_err(|e| format!("bad input {:?}: {}", s, e))
}

fn main() {
    println!("{:?}", parse("4x"));
}

What is printed?
  • aErr("bad input \"4x\": invalid digit found in string")
  • bErr("bad input 4x: ParseIntError { kind: InvalidDigit }")
  • cErr(ParseIntError { kind: InvalidDigit })
  • dOk(4), as parse reads the leading digits and stops at x
Explanation:map_err replaces the error type: the closure receives the ParseIntError and returns a String, so the function now yields Result<i32, String>. Inside the closure {:?} on s adds quotes ("4x") and {} on the error uses its Display text invalid digit found in string. The outer {:?} on the Result then prints the String with escaped quotes. str::parse never accepts trailing garbage, so "4x" is a full failure, not a partial Ok(4).

Test yourself against the 3750-question Backend bank.

Start interview