Avoid checking if error is nil repetition?

前端 未结 6 2089
无人及你
无人及你 2021-01-30 03:50

I\'m currently learning go and some of my code looks like this:

a, err := doA()
if err != nil {
  return nil, err
}
b, err := doB(a)
if err != nil {
  return nil         


        
6条回答
  •  长发绾君心
    2021-01-30 04:19

    It looks wrong to you perhaps because you are used to not handling errors at the call site. This is quite idiomatic for go but looks like a lot of boilerplate if you aren't used to it.

    It does come with some advantages though.

    1. you have to think about what the proper way to handle this error is at the site where the error was generated.
    2. It's easy reading the code to see every point at which the code will abort and return early.

    If it really bugs you you can get creative with for loops and anonymous functions but that often gets complicated and hard to read.

提交回复
热议问题