Home >Backend Development >Golang >Does `break` Exit a `switch/select` or its Enclosing Loop in Go?

Does `break` Exit a `switch/select` or its Enclosing Loop in Go?

DDD
DDDOriginal
2024-12-30 03:09:08683browse

Does `break` Exit a `switch/select` or its Enclosing Loop in Go?

Does a break Statement Break from a Switch/Select or Escape the Loop It Resides in?

Many programming languages employ the switch/select statement to handle multiple cases, typically breaking automatically after each case execution. However, in Go, does a break statement within a switch/select statement solely terminate the switch/select block or cause an exit from the enclosing loop?

Answer:

In Go, a break statement exits the innermost for, switch, or select statement. If a label is provided, it must match the label of the enclosing loop, switch, or select construct.

The following excerpt from The Go Programming Language Specification clarifies this behavior:

Break statements, The Go Programming Language Specification.

A "break" statement terminates execution of the innermost "for",
"switch" or "select" statement.

BreakStmt = "break" [ Label ] .

Therefore, in the provided example:

for {
    switch sometest() {
    case 0:
        dosomething()
    case 1:
        break
    default:
        dosomethingelse()
    }
}

The break statement terminates only the switch statement, not the enclosing for loop.

The above is the detailed content of Does `break` Exit a `switch/select` or its Enclosing Loop in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn