tezvyn:

Rust's operator equivalent to Go's if err != nil return err

AI-drafted, machine-checkedSource: doc.rust-lang.orgbeginner

Tests if you know Rust's ? operator for error propagation. A strong answer names ?, explains it returns Err from the function via Result's Try and FromResidual traits, and unwraps Ok. Red flag: calling it .unwrap() or suggesting manual match is idiomatic.

WHAT THIS TESTS: This question tests whether you know the idiomatic Rust syntax for early-return error propagation and understand how it interacts with the standard library Result type. It checks if you can contrast Go's explicit verbosity with Rust's postfix operator and whether you understand the underlying trait machinery that makes it work.

A GOOD ANSWER COVERS: First, name the operator: the postfix question mark, written as ?. Second, explain the behavior on Result: if the value is Err, the operator immediately returns that error from the current function; if the value is Ok, it evaluates to the inner success value and execution continues. Third, note that this works because Result implements the Try trait and integrates with FromResidual, allowing the error to propagate with potential type conversion. Fourth, mention that Result is an enum with exactly two variants: Ok containing the success value, and Err containing the error value.

COMMON WRONG ANSWERS: Confusing ? with unwrap or expect, which panic on Err rather than returning. Suggesting that ? is merely syntactic sugar for a manual match block without mentioning the Try and FromResidual trait system that enables automatic error conversion. Claiming that Rust requires explicit error handling at every call site like Go, or stating that ? works on Option in exactly the same way without noting the return type constraints.

LIKELY FOLLOW-UPS: How does ? handle error type conversion when the function returns a different error type? When can you use ? inside a closure versus the enclosing function? What changed in recent Rust editions regarding ? in main or test functions? How does the Try trait differ from older approaches?

ONE CONCRETE EXAMPLE: Imagine a function that returns Result<i32, &str>. Inside it, you call another function that also returns Result<i32, &str> and bind it with let x = some_call()?;. If some_call returns Err containing an error message, the ? operator immediately returns that Err variant from the outer function. If some_call returns Ok containing an integer, x is bound to that i32 value and execution proceeds. This replaces roughly four lines of explicit Go-style checking with a single postfix operator.

Read the original → doc.rust-lang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.