Avoid checking if error is nil repetition?

前端 未结 6 2072
无人及你
无人及你 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:45

    You could use named return parameters to shorten things a bit

    Playground link

    func doStuff() (result string, err error) {
        a, err := doA()
        if err != nil {
            return
        }
        b, err := doB(a)
        if err != nil {
            return
        }
        result, err = doC(b)
        if err != nil {
            return
        }
        return
    }
    

    After you've been programming in Go a while you'll appreciate that having to check the error for every function makes you think about what it actually means if that function goes wrong and how you should be dealing with it.

提交回复
热议问题