3 ms·
I have been using Zig a lot lately, and I just want to share the equivalent of the let-else solution in Zig: const user = getUser() orelse return error.NoUs
by Zambyte 1y ago
I have been using Zig a lot lately, and I just want to share the equivalent of the let-else solution in Zig:
const user = getUser() orelse return error.NoUser;
If you only need user for a narrow scope like you would get from match, you can also use if to unwrap the optional.
if (getUser()) |user| {
// use user
} else {
return error.NoUser;
}
- robertlagrant 1y agoAnd the same in Python: if user := get_user() is not None: # use user else: # return error Although given the happy path code can mean you don't see the error condition for ages, I much prefer this: if (user := get_user()) is None: # return error # use user
- 38 1y agoPython doesn't have option, so this is not the same thing at all
- robertlagrant 1y agoWhat if get_user() returns something of type Optional[User]? Does that get it close enough?
- aatd86 1y agohehehe. reminds me of if err != nil in Go which is really not an issue in my opinion. But it seems to have become somewhat infamous in some circles.
- jimbokun 1y agoThe problem is the compiler doesn’t help you if you forget to check err. Although it will flag unused variable. So you will have to make an effort to deliberately ignore the error value. Still not quite as nice as the compiler forcing you to handle the error case.
- int_19h 1y agoThe problem is that idiomatic Go reuses err for multiple calls. So if you already have one call and check err after, it counts as used, and forgetting to check it on subsequent calls is not flagged.
- aatd86 1y agoTrue. Not a big issue in practice and there are linters and whatnot. Variable shadowing can happen. But it's a bit orthogonal of a concern. I do have things to say about errors but my complaints are a bit more nuanced and made with hindsight.
- LtWorf 1y agoIt is a massive problem. It's basically the worse thing about C and they decided to copy it. Easily 60-70% of all go code is about propagating errors to the caller directly.
- aatd86 1y agoNot C. C errors are different since they are simply numbers. And spoiler alert, every language propagates errors. Sometimes automatically via exception handling, somewhat simply by returning error values. rust does this too. Matter fact, even javascript might be creeping toward this model of explicit error propagation soon. Good, because it is easier to understand.
- LtWorf 1y agoEasier to understand and even easier to get it wrong!
- fjasdfas 1y ago`:=` was new to me: https://peps.python.org/pep-0572/ https://peps.python.org/pep-0572/ It actually looks really natural in python, glad they added.
- fjasdfas 1y agogleam: fn get_user_name() -> Result(String, String) { use user <- result.map(option.to_result(get_user(), "No user")) user }