Why can't the "?" operator cannot be used in workflow
⚓ Rust 📅 2026-01-19 👤 surdeus 👁️ 9I was trying to quickly drop some test results in a file for verification and ended up wanting to use the "?" operator in a scope. For instance:
struct MyErr {}
fn plop() -> Result<i32, MyErr> {
Ok(42)
}
fn plap() -> Result<i32, MyErr> {
Ok(43)
}
fn main() {
let a: Result<i32, MyErr> = {
Ok(plop()? + plap()?)
};
println!("{:?}", a);
}
which for me "should work" in the sense that my scope return a value, thus this value can be a result, the result type are compatible, etc.. but I get this error:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/main.rs:12:18
|
10 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
11 | let a: Result<i32, MyErr> = {
12 | Ok(plop()? + plap()?)
| ^ cannot use the `?` operator in a function that returns `()`
|
help: consider adding return type
|
10 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
11 | let a: Result<i32, MyErr> = {
...
15 | println!("{:?}", a);
16 + Ok(())
where it seems that the "?" is catched by the main method instead of the scope. Is this normal or a bug ? Found it a bit confusing that the scope did not catch this operator.
3 posts - 3 participants
🏷️ Rust_feed