Go: Allow main() to return error

Created on 3 Oct 2019  路  6Comments  路  Source: golang/go

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
}
FrozenDueToAge

Most helpful comment

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.

All 6 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

enoodle picture enoodle  路  3Comments

OneOfOne picture OneOfOne  路  3Comments

natefinch picture natefinch  路  3Comments

mingrammer picture mingrammer  路  3Comments

bbodenmiller picture bbodenmiller  路  3Comments