2 ms·
I was thinking of `guard` in Swift when I was writing but I haven't used it so I was unsure of its exact semantics. It is a bit of a shame it is only useable on
by zoogeny 3y ago
I was thinking of `guard` in Swift when I was writing but I haven't used it so I was unsure of its exact semantics. It is a bit of a shame it is only useable on optionals and not on arbitrary types.
Nice to see a full pattern matching guard in Rust. I think the terminating `?` operator makes it a bit less necessary as I would guess a large portion of cases where I would want that early-return behavior I would just take advantage of that operator. But their choice to reuse `else` makes a lot of sense and the pattern reads well.
I was watching the recent Rust stream by Jon Gjengset where he builds a BitTorrent implementation [1]. One thing he did frequently was add a `.context` method to function invocations that would terminate in `?`. My assumption just looking at that pattern is that it would allow the error system to tag the errors to help guide the programmer to the specific line the error was generated from, almost like an annotated stack trace. But again, I don't have direct experience programming large Rust applications.
The reason I consider this topic is because this kind of error handling would be ideal in Go. I often end up with the classic pattern:
if value, err := someFunc(); !err {
// value is useable
}
// handle err
And I would just really, really like if Go would let me:
if value, err := someFunc(); err != nil {
// handle err
}
// value is useable
But, I suppose due to Go block scoping `value` is only valid within the if block.
1. https://www.youtube.com/watch?v=jf_ddGnum_4&t=9465s&ab_channel=JonGjengset https://www.youtube.com/watch?v=jf_ddGnum_4&t=9465s&ab_chann...