4 ms·
I thought it would be a deal breaker for me, too. C/C++/C#/Python have been my standard languages... but after coding in it for a while, I love it. You never ha
by NateDad 14y ago
I thought it would be a deal breaker for me, too. C/C++/C#/Python have been my standard languages... but after coding in it for a while, I love it. You never have to worry if someone downstream is going to throw an exception make your function exit before it gets to the end. That means you can write robust code without needing a ton of try/catch everywhere, or using statements (from C#) or whatever.
Yes, there's some of this:
if f, err := io.Open("foo.txt"); err != nil {
return err
} else {
// use f
}
However, that's not really any more code than
try:
f = open("foo")
// use f
except IOError as e:
return e // or throw, or whatever
Plus Go uses multiple returns everywhere, so you don't have to worry about errors being confused with actual data returned.
It's pretty awesome.
- jgeralnik 14y agoDon't bother with the else. Just continue with your code outside a nested block since the if returns.
- NateDad 14y agoin this case, f is locally scoped to the if/else statement since it's assigned inside the if statement... Probably most of the time I would actually assign it outside the if statement and then check it/return and not have the rest of the code indented.