In Rust, why can't `?` be applied to an `Option` inside a function that returns `Result`, and how do you bridge the two?
answer
- no automatic Option to Result
- None carries no error
- the compiler suggests ok_or
- ok() discards the error
basics
~10 sThe ? operator on an Option can only return None, which a Result-returning function cannot return, so rustc reports E0277. Bridge explicitly: ok_or or ok_or_else makes a Result, and ok() makes an Option.
solid answer
~40 s`?` works on an `Option` inside a function returning `Option`, where `None` propagates as `None`, and on a `Result` inside a function returning a compatible `Result`. It never converts one into the other, because a `None` carries no error value to put in an `Err`, and an `Err` holds information `None` would throw away. rustc reports E0277, "the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`", and suggests `.ok_or(...)?`. So write `opt.ok_or(err)?` (or `ok_or_else` when building the error is costly) in a `Result` function, and `res.ok()?` in an `Option` function when discarding the error is acceptable. The `?` after `ok_or` still applies `From`, so `ok_or("empty")?` works in a function returning `Result<_, String>`.
code
rust · 11 linesuse std::collections::HashMap;
fn server_addr(cfg: &HashMap<String, String>) -> Result<String, String> {
let host = cfg.get("host")?; // Option used with ? in a Result-returning fn
Ok(host.clone())
}
fn main() {
let cfg = HashMap::new();
println!("{:?}", server_addr(&cfg));
}go deeper
Recall that ? on an Option needs a function returning Option, and ? on a Result needs one returning Result; there is no mixing.
Explain why no automatic bridge exists, None has no error and Err would lose one, and use ok_or, ok_or_else and ok() to cross explicitly.
Decide per call whether a caller needs the reason: collapsing failures with ok() is a lossy choice to make on purpose, not a way to silence E0277.
Set a team expectation that absence and failure are modelled differently, so Option-returning helpers do not quietly swallow errors that callers later need.
## The rule In Rust, `?` propagates the "failure" case of the value it is applied to, and that failure has to fit the enclosing function's return type: - `?` on an `Option<T>`: `Some(v)` evaluates to `v`; `None` returns `None`. The function must return an `Option`. - `?` on a `Result<T, E>`: `Ok(v)` evaluates to `v`; `Err(e)` returns `Err(From::from(e))`. The function must return a `Result` whose error type converts from `E`. What `?` will **not** do is cross between the two. The Rust Book says it plainly: you can use `?` on a `Result` in a function that returns `Result` and on an `Option` in a function that returns `Option`, "but you can't mix and match". ## Why there is no automatic bridge The two directions fail for different reasons: 1. **`Option` into a `Result` function.** A `None` carries no error value. To return `Err(...)`, something has to invent the error, and the compiler will not choose one for you. 2. **`Result` into an `Option` function.** An `Err(e)` carries information. Turning it into `None` silently throws that away, so Rust makes you write the discarding step yourself. Both mismatches are reported as **E0277**. In a function returning `Result<String, String>`, `cfg.get("host")?` produces "the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`", with the hint "use `.ok_or(...)?` to provide an error compatible with `Result<String, String>`". The reverse case, `line.trim().parse::<u16>()?` in a function returning `Option<u16>`, produces "the `?` operator can only be used on `Option`s, not `Result`s, in a function that returns `Option`", with the hint "use `.ok()?` if you want to discard the `Result<Infallible, ParseIntError>` error information". ## Bridging in each direction | You have | Function returns | Write | Effect on failure | |---|---|---|---| | `Option<T>` | `Option<U>` | `opt?` | returns `None` | | `Option<T>` | `Result<U, F>` | `opt.ok_or(err)?` | returns `Err(From::from(err))` | | `Option<T>` | `Result<U, F>` | `opt.ok_or_else(\|\| make_err())?` | builds the error only on `None` | | `Result<T, E>` | `Option<U>` | `res.ok()?` | discards `E`, returns `None` | | `Result<T, E>` | `Result<U, F>` | `res?` | returns `Err(From::from(e))` if `F: From<E>` | Two details are easy to miss: - **`From` still runs after `ok_or`.** `ok_or("config file is empty")` produces a `Result<&str, &str>`. In a function returning `Result<u16, String>`, the following `?` converts the `&str` error into a `String` with `From<&str> for String`. The same works for `Box<dyn Error>`, which std can build from a `&str` or a `String`. - **`ok_or` evaluates its argument eagerly.** `ok_or(format!(...))` allocates the message even when the value is `Some`. `ok_or_else` takes a closure and calls it only on `None`. The combinators themselves, and when to prefer each, belong to the material on `Option` and `Result`. ## A worked example: a CLI reading a config A tool keeps its settings in a `HashMap<String, String>` and in a text file whose first line is a port: - In a lookup that returns `Option<u16>`, `text.lines().next()?` handles an empty file and `line.trim().parse::<u16>().ok()?` handles a malformed number. Both failures become `None`, and the caller cannot tell them apart. - In the variant that returns `Result<u16, String>`, `text.lines().next().ok_or("config file is empty")?` names the empty-file case, and `map_err` names the parse case with the offending line. The caller now gets a reason. Choosing between them is a question of what the caller needs: `Option` says "absent", `Result` says "failed, and here is why". ## Common mistakes - Expecting `None` to turn into some default `Err` automatically. There is no default error; the code does not compile. - Writing `.ok()?` in a `Result` function. `ok()` produces an `Option`, so this is the same E0277 in disguise. - Writing `.unwrap()` to make the types line up. It compiles, but a missing key now panics instead of being reported. - Reaching for `.err()?` when `.ok()?` was meant. `err()` keeps the error and drops the success value, so it returns `None` exactly when the operation succeeded. - Putting an expensive `format!` inside `ok_or` in a hot path, where `ok_or_else` would build it only on failure. - Trying `fn main() -> Option<()>` so that `?` on an `Option` works in `main`. `Option` does not implement `Termination`, so rustc reports E0277, "`main` has invalid return type `Option<()>`". In `main`, an `Option` always needs `ok_or` (or `ok_or_else`) before `?`, with `main` returning a `Result`.
- Why does `text.lines().next().ok_or("empty")?` compile in a function returning `Result<u16, String>`?`ok_or("empty")` yields a `Result<&str, &str>`. The `?` then returns `Err(From::from(e))`, and std implements `From<&str> for String`, so the `&str` error is converted into the function's `String` error. The same `?` conversion is what lets a `&str` become a `Box<dyn Error>`.
- What does `?` do on a `Result<Option<T>, E>`?It applies to the outer `Result`: an `Err` returns early, and an `Ok` yields the inner `Option<T>`. Handling the `Option` takes a second step, such as `ok_or(...)?` in a `Result` function. `?` never looks inside nested wrappers on its own.
- ? on None in a Result function returns some default Err value
- ? converts between Option and Result automatically in both directions
- Calling .ok()? still lets the caller see the original error
- ok_or and ok_or_else are interchangeable in every situation
- Writing .unwrap() is a fine way to make Option fit a Result function