Avoid checking if error is nil repetition?

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

    You could create context type with result value and error.

    type Type1 struct {
        a int
        b int
        c int
    
        err error
    }
    
    func (t *Type1) doA() {
        if t.err != nil {
            return
        }
    
        // do something
        if err := do(); err != nil {
            t.err = err
        }
    }
    
    func (t *Type1) doB() {
        if t.err != nil {
            return
        }
    
        // do something
        b, err := t.doWithA(a)
        if err != nil {
            t.err = err
            return
        }
    
        t.b = b
    }
    
    func (t *Type1) doC() {
        if t.err != nil {
            return
        }
    
        // do something
        c, err := do()
        if err != nil {
            t.err = err
            return
        }
    
        t.c = c
    }
    
    func main() {
    
        t := Type1{}
        t.doA()
        t.doB()
        t.doC()
    
        if t.err != nil {
            // handle error in t
        }
    
    }
    

提交回复
热议问题