Hacker News new | ask | show | jobs
by robertlagrant 403 days ago
And 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
3 comments

`:=` was new to me: https://peps.python.org/pep-0572/

It actually looks really natural in python, glad they added.

hehehe. 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.
It 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.

Not 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.

Easier to understand and even easier to get it wrong!
The 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.

The 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.
True. 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.

Python doesn't have option, so this is not the same thing at all
What if get_user() returns something of type Optional[User]? Does that get it close enough?