by valenterry · 4y ago · 0 comments
Without them, using typed errors is very clumsy. Optimally, you would write the following code:
fn foo(r1: Result<i32, Error1>, r: Result<i32, Error2>) {
let i1 = r1?;
let i2 = r2?;
// ...
}
and Rust would infer the return type to be Result<String, Error1 | Error2>
without having to do any extra definitions or conversions. #[derive(thiserror::Error, Debug)]
enum Error {
#[error("One")]
One(#[from] Error1),
#[error("Two")]
Two(#[from] Error2),
}
fn foo(r1: Result<i32, Error1>, r2: Result<i32, Error2>) -> Result<..., Error> {
let i1 = r1?;
let i2 = r2?;
// ...
}
Whereas for binaries, people usually recommend anyhow. Code sample[1]: fn foo(r1: Result<i32, Error1>, r2: Result<i32, Error2>) -> anyhow::Result<...> {
let i1 = r1?;
let i2 = r2?;
// ...
}
[0]: https://play.rust-lang.org/?version=stable&mode=debug&editio...
[1]: https://play.rust-lang.org/?version=stable&mode=debug&editio...The pattern I use in my app is to use thiserror, and then just have an anyhow catch-all. That lets me do specific stuff where I know I'm going to need specific handling, and an easy-to-use fallback for just saying "this bad thing happened" with the anyhow! macro.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Not logged in")]
NotLoggedIn,
#[error(transparent)]
Api(#[from] ApiError),
// etc
#[error(transparent)]
Other(#[from] anyhow::Error),
}
I don't know if this is the best pattern but it's worked really well for me. fn read_string() -> std::io::Result<String> {
Ok("123".to_owned())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let s = read_string()?; // io::Error
let n = i32::from_str_radix(&s, 10)?; // num::ParseIntError
println!("read number: {n}");
Ok(())
}The return type is part of the function signature and Rust deliberately doesn't infer signatures, in languages with "too much" inference it's impractical for the human programmer to keep track of types because it's all inferred, this has started to be a problem in C++ as more and more things are auto. Rust has some very sophisticated inference inside a function (including partial inference and inferring types from how they're later used), but none for the signature.
[1]: https://play.rust-lang.org/?version=stable&mode=debug&editio...
Allowing _ in return position only for private functions feels like something that ends up surprising 99% of people either that this works, or that it doesn't work for their public function and neither group of people are filled with joy as a result.
It's not a hill I'd die on, but it would go on my list of things I don't like in Rust, along with most as casts, impl AddAssign for String, is_ascii_predicates(/* taking */ &self)
While codeblocks `fn1(fn2(), fn3)` and `var r1 = fn2(); var r2 = fn3; fn1(r1, r2)` are more or less identical, unless you have static type definitions for these methods you start having a very bad time inferring what types are being passed around.
Consider typical python wrapper library with liberal use of *kwargs to pass non-wrapped arguments down to wrappee. Those arguments and their types (as much as they are available in python, you get the idea) are entirely missing from wrapper code and make changes at call site pretty difficult
It doesn't matter if the types are annotated explicitly or inferred. The amount of information is 100% the same. The IDE could just fill in the types _exactly_ in the same way as they would look like when annotated by hand - maybe just with a different color.
IntelliJ does this quite well, see for instance: https://i.stack.imgur.com/tiqjc.png
This is not a guess. This is the real types. There is literally no difference in the behaviour/semantics of the code.
> Consider typical python wrapper library with liberal
No, because python is not statically typed. You can't compare that.
let a = if cond {
1
} else {
1.0
};
a + 3
Now, the error would be pushed to the `+` operator because there isn't an `Add` for `f32 | u32`. Granted, this is a trivial example, and a programmer can easily see through it, but in general this can get very overwhelming and cause errors to leave their 'root cause'. class A {
x = 10;
scale(n: number): void {
this.x *= n;
}
}
class B {
y = 10;
scale(n: number): void {
this.y *= n;
}
}
var z: A | B;
z = new A
z.scale(2);
z = new B
z.scale(2);
I was also looking for Sum Types/anonymous enums[0].[0] https://news.ycombinator.com/threads?id=karmakaze&next=33505...
Why not? It makes total sense for one to exist. This is something the language needs to deal with, not the programmer. But the programmer always sprinkle annotations so that errors can only reach so far.
I disagree: IME, when you add a float and an integer, you want to cast float to integer 50% of the time, and integer to float the remaining 50% of the time.
Even if it leads to more verbosity, I prefer arithmetic operations to be endomorphisms and use explicit casts.
But also, for every developer with a couple of month experience, this is not a new problem. It happens all the time, be it missing some parens or a dot or a return / semicolon (depending on the language of course).
Usually it's very easy to hunt it down - you see "a + 1" and you say "wait, a should be an integer - why is it not" and then you go back from there. But in general I agree that it adds some time in such cases that would be resolved quicker with annotations everywhere.
Of course this is just a minimal example... Others have talked about the real point of this comment, and it's just a minor nit. I wanted to point this out for new rust programmers reading this.
Of course, if you care about which error is from which function, you can always easily do that by wrapping them into a sumtype, but in practice this is a rather rare use-case in application code at least.
But otherwise we can. And this is something that we will know at compile-time, so we can prevent runtime-checks that would not work.
That would make precise error handling on libraries quite a bit better.