iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article

The Mystery of the Switch Statement (Not Really)

に公開

Well, I came across an interesting tweet (the answer is already out, so it should be fine).

I totally fell for it (lol).

You can see what happens if you actually write and run it.

package main

func f() bool {
    return false
}

func main() {
    switch f()
    {
    case true:
        println(1)
    case false:
        println(0)
    }
}

If you try it out, you'll see that it actually prints 1 instead of 0. The key point is the position of the opening brace for the switch statement.

According to the Go specification, an expression switch statement is defined as follows:

ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
ExprCaseClause = ExprSwitchCase ":" StatementList .
ExprSwitchCase = "case" ExpressionList | "default" .

Looking at this, you can see that a statement and an expression can be written between the switch token and the opening brace. In other words, the code mentioned above is equivalent to the following:

switch _ = f(); true {
case true:
    println(1)
case false:
    println(0)
}

By the way, if you run the original code through a formatting tool, it will be formatted as follows:

package main

func f() bool {
    return false
}

func main() {
    switch f(); {
    case true:
        println(1)
    case false:
        println(0)
    }
}

This makes it much easier to understand, doesn't it?

So, when you write Go code, be sure to format and check it frequently. Well, some modern editors even handle formatting automatically.

GitHubで編集を提案

Discussion