log.Panicf() not as good as panic(); or, the case for NoReturn

703 views
Skip to first unread message

Chucky Ellison

unread,
Mar 1, 2015, 12:43:26 PM3/1/15
to golan...@googlegroups.com
Go is quite happy with the following program:

package main

import "fmt"
// import "log"

func foo
(x int) int {
    if x == 0 {
        return 0
    }
    // log.Panicf("Not yet handling case %d", x)
    panic
(fmt.Sprintf("Not yet handling case %d", x))
}

func main
() {
    foo
(0)
}

Because panic() is considered a terminating statement, it eliminates foo()'s responsibility of returning an int in that case.  The program compiles and runs.  However, if you swap the panic() with the commented log.Panicf() line (and of course swap the imports), Go complains:

.\panic.go:12: missing return at end of function

It seems that there's no way to inform the compiler that log.Panicf() (and other similar functions) should be considered terminating statements.  Having a way to do this would allow using the Panic wrappers just like panic, as well as letting users make their own such functions (that contain an infinite loop, or call exit, etc).

C11 introduced a _NoReturn function specifier (n1570.pdf Sec 6.7.4:8, based on document http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1478.htm) to do exactly this.  Their primary objective was to eliminate the need for warnings, which in Go's case, are actually errors.  Perhaps something similar could be considered for Go.

Thoughts?

Carlos Castillo

unread,
Mar 1, 2015, 3:14:10 PM3/1/15
to golan...@googlegroups.com
In the very rare case that this is actually a problem, you could just put an empty panic after it to suppress the error.

It's not worth it, especially if anyone could improperly mark their functions as no return, and thus intentionally or not cause problems for the users of their packages.

Dave Cheney

unread,
Mar 1, 2015, 3:33:50 PM3/1/15
to golan...@googlegroups.com
Looks like it would be easlier to use panic directly. 

log.Panicf was added before we had the return rules in go 1.1. With 20/20 hindsight it's clear that it's less useful now, just use panic.

Ian Lance Taylor

unread,
Mar 1, 2015, 6:51:10 PM3/1/15
to Chucky Ellison, golang-nuts
On Sun, Mar 1, 2015 at 9:43 AM, Chucky Ellison <cmel...@gmail.com> wrote:
>
> C11 introduced a _NoReturn function specifier (n1570.pdf Sec 6.7.4:8, based
> on document http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1478.htm) to do
> exactly this. Their primary objective was to eliminate the need for
> warnings, which in Go's case, are actually errors. Perhaps something
> similar could be considered for Go.

People can write their own panic or return statement to avoid the
compilation error. I think the cost of doing that in the relatively
cases where this arises is less than the cost of making the language
more complex.

Ian
Reply all
Reply to author
Forward
0 new messages