Home >Backend Development >Golang >Does `break` Exit a `switch` or the Outer Loop in Go?

Does `break` Exit a `switch` or the Outer Loop in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 18:15:10297browse

Does `break` Exit a `switch` or the Outer Loop in Go?

Does a Break Statement Exit a Switch/Select or Outer Loop?

In Go, break statements terminate execution of the innermost for, switch, or select statement.

Code Example:

for {
    switch sometest() {
    case 0:
        dosomething()
    case 1:
        break // Break from the switch statement
    default:
        dosomethingelse()
    }
}

According to the Go Programming Language Specification, if a break statement has a label, it must refer to an enclosing for, switch, or select statement. If no label is provided, the statement terminates execution of the innermost such statement.

Therefore, in the provided example, the break statement terminates execution of the switch statement, not the outer for loop. The execution will resume after the switch statement, continuing the loop.

The above is the detailed content of Does `break` Exit a `switch` or the Outer 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