Answer#
value? means "if this is an Err, return it from here; if it is Ok, give me the inside". A function whose return type is () has nowhere to return an error to, so the compiler refuses (error E0277). The usual place to meet this is main.
fn main() {
let n: i32 = "42".parse()?;
println!("{n}");
}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:2:30
|
1 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
2 | let n: i32 = "42".parse()?;
| ^ cannot use the `?` operator in a function that returns `()`
|
help: consider adding return type
|
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
2 | let n: i32 = "42".parse()?;
3 | println!("{n}");
4 + Ok(())
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0277`.The answers below are the two valid ways to fix it.