2015-04-15 15:20
浏览 85


Go has a very unfortunate lack of built-in assertions. I want to implement them this way:

const ASSERT = true

func SomeFunction() {
        if ASSERT && !some_condition_that_should_always_be_true() {
                panic("Error message or object.")

My question is will the if-statement be optimized out if I define const ASSERT = false?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongsha1544 2015-04-15 15:30

    As noted by the people in the comments to your question, it's implementation-specific.

    gc does remove it. You can build your program with -gcflags '-S' and see that the ASSERT part is not in the binary.

    E.g. compile the following code with -gcflags '-S', and you'll see that the code on lines 8 and 9 is included, but change Assert to be false, and they won't be there in the asm listing.

    package main
    const Assert = true
    var cond = true
    func main() {
        if Assert && !cond {


    As for gccgo, it removes this code at -O1 and above. You can see it by compiling the same code with

    go build -compiler gccgo -gccgoflags '-O1' main.go

    and then doing

    objdump -S main

    to see the annotated assembly.

    解决 无用
    打赏 举报