Handling multiple errors in go

前端 未结 4 1296
生来不讨喜
生来不讨喜 2020-12-17 19:17

I\'m new to go and finding the error handling to be extremely verbose. I\'ve read the reasoning for it and mostly agree, but there are a few places where it seems like ther

4条回答
  •  爱一瞬间的悲伤
    2020-12-17 19:48

    For idiomatic, refer to peterSO's answer which begins to touch on the subject of returning errors, and this can be taken further by wrapping errors with some extra bit of information related to the context of the call within your application.

    There may be cases where iterative runs over an operation might warrant something more generalized with some unusually creative examples in the following link, but as I commented on that question, it was a bad code example to examine: Go — handling multiple errors elegantly?

    Regardless, looking solely at the example you have, this is nothing more than a one-off in main, so treat it like such if you're just looking to mess around as one might do in an interactive python console.

    package main
    
    import (
        "fmt"
        "io"
        "io/ioutil"
        "os/exec"
    )
    
    func main() {
        cmd := exec.Command("cat", "-")
        stdin, _ := cmd.StdinPipe()
        stdout, _ := cmd.StdoutPipe()
    
        cmd.Start()
        io.WriteString(stdin, "Hello world!")
    
        stdin.Close();
        output, _ := ioutil.ReadAll(stdout)
    
        fmt.Println(string(output))
    }
    

提交回复
热议问题