Open mateiandrei94 opened 7 months ago
As documented in The Rust Reference chapter titled The question mark operator:
When applied to values of the
Result<T, E>
type, it propagates errors. If the value isErr(e)
, then it will returnErr(From::from(e))
from the enclosing function or closure.
This use of the From
trait is really useful, as it enables the type of error on which ?
is applied to be anything that can convert into the error that the enclosing function returns. However, if the compiler does not know what type that is, you will necessarily have an inference error.
@eggyal Thank you, yes, I understand and am aware that ?
uses From::from(err)
, I also mentioned it a comment in the example (see below), however as stated in the first sentence in my bug report: I believe that in certain scenarios the question mark operator should infer the err variant of a result type. By that I don't mean change the behavior of the ?
operator, but rather that inference::<_, VarError, _>
should be automatically added silently, in which case the ?
would work fine using From::from
.
As stated in the form of comments in the code example, the compiler already infers T
in Result<T, E>
I'm simply saying that when E
is not known it should be inferred in the same way that T
is.
I'll update here my expectations:
1) in the case the error variant in 100% known, it cannot be anything else inference::<_, VarError, _>
should be added.
2) in the case where we use ?
but it doesn't always return the same E
type annotations should be needed
// works fine
let x = inference(|| {
let result = std::env::var("key");
// attempt to do what let result = result?; would do
let result = match result {
Ok(ok) => ok,
Err(err) => {
// the compiler "knows" that err : VarError
return Err(err); // the ? operator uses From::from(err) <<<<<<<<<< Here
},
};
Ok(result)
});
I believe that in certain scenarios the question mark operator should infer the err variant of a result type
I tried this code:
I expected to see this happen: everything to compile, because all the types are actually known, I would've understood a
type annotations needed
compile error if I had multiple Err return points with different error types in which case inference would not have been possible.Instead, this happened: compile error
type annotations needed
Meta
rustc --version --verbose
: