Avoid checking if error is nil repetition?

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

    You can pass an error as a function argument

    func doA() (A, error) {
    ...
    }
    func doB(a A, err error)  (B, error) {
    ...
    } 
    
    c, err := doB(doA())
    

    I've noticed some methods in the "html/template" package do this e.g.

    func Must(t *Template, err error) *Template {
        if err != nil {
            panic(err)
        }
        return t
    }
    

提交回复
热议问题