Hi there, I'm experimenting with Rustlings, and I stumbled upon question 52, where the code looks like this:
fn main() -> Result<(), ParseIntError> {
// [...]
let cost = total_cost(pretend_user_input)?;
// [...]
Ok(())
}
In the Rust book, I see that
error values that have the
?
operator called on them go through thefrom
function, defined in theFrom
trait in the standard library, which is used to convert values from one type into another. When the?
operator calls thefrom
function, the error type received is converted into the error type defined in the return type of the current function.
But if I try to convert from i32
into ()
manually using from
, I get errors:
let a: () = From::from(3 as i32);
error[E0277]: the trait bound `(): From<i32>` is not satisfied
--> exercises/13_error_handling/errors3.rs:32:28
|
32 | let a: () = From::from(3 as i32);
| ---------- ^^^^^^^^ the trait `From<i32>` is not implemented for `()`
| |
| required by a bound introduced by this call
|
= help: the following other types implement trait `From<T>`:
<(T, T) as From<[T; 2]>>
<(T, T, T) as From<[T; 3]>>
<(T, T, T, T) as From<[T; 4]>>
<(T, T, T, T, T) as From<[T; 5]>>
<(T, T, T, T, T, T) as From<[T; 6]>>
<(T, T, T, T, T, T, T) as From<[T; 7]>>
<(T, T, T, T, T, T, T, T) as From<[T; 8]>>
<(T, T, T, T, T, T, T, T, T) as From<[T; 9]>>
and 4 others
For more information about this error, try `rustc --explain E0277`.
error: could not compile `exercises` (bin "errors3") due to 1 previous error
and
let a: () = <()>::from(3 as i32);
error[E0308]: mismatched types
--> exercises/13_error_handling/errors3.rs:32:28
|
32 | let a: () = <()>::from(3 as i32);
| ---------- ^^^^^^^^ expected `()`, found `i32`
| |
| arguments to this function are incorrect
|
note: associated function defined here
--> /home/abertulli/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/convert/mod.rs:585:8
|
585 | fn from(value: T) -> Self;
| ^^^^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `exercises` (bin "errors3") due to 1 previous error
So, how is a i32
converted into the unit type ()
, when using the ?
operator? Thanks!