Right now the compiler reports an error if main() returns an error
sandbox/foobar/main.go:5:6: func main must have no arguments and no return values
A throwaway script typically uses a log.Fatalln to exit on error:
func main() {
err := doSomething()
if err != nil {
log.Fatalln(err)
}
err = doSomethingElse()
if err != nil {
log.Fatalln(err)
}
}
It would be nice to just return the error, and get the same effect as calling log.Fatalln(err):
func main() error {
err := doSomething()
if err != nil {
return err
}
err = doSomethingElse()
if err != nil {
return err
}
return nil
}
You can do the same thing with
func main() {
var err error
defer func() {
if err != nil {
log.Fatalln(err)
}
}()
err = doSomething()
if err != nil {
return
}
err = doSomethingElse()
if err != nil {
return
}
}
Returning error from main sends something outside the programmer's control. You might want to control how/where the error is shown.
Don't use defer magic for this... just move the code into another function that returns an error:
package main
func main() {
if err := run(); err != nil {
}
}
func run() error {
return nil
}
actually maybe i'll leave this open. In fact, I personally do it the way @DisposaBoy suggested. In which case, run becomes another name for main()
Why a log.Fatalln and not something else? With what logger? What if the main function panics before returning?
I think this complicates the language (https://golang.org/ref/spec#Program_execution) for very little benefit - just saving yourself four lines of code.
This was proposed (and rejected) in #27328, and as far as I can tell this report does not add any new motivating data on top of that, so closing.
Duplicate of #27328
Most helpful comment
Why a
log.Fatallnand not something else? With what logger? What if the main function panics before returning?I think this complicates the language (https://golang.org/ref/spec#Program_execution) for very little benefit - just saving yourself four lines of code.