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

Does `break` Exit a Switch or the Surrounding Loop in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-29 11:57:11764browse

Does `break` Exit a Switch or the Surrounding Loop in Go?

Does a "break" Statement Exit a Switch/Select Block or the Loop?

The "break" statement in Go is used to terminate the execution of the innermost enclosing "for", "switch", or "select" statement.

In the provided code snippet:

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

The "break" statement will only exit the innermost enclosing "switch" block. This is because the "switch" statement is the innermost enclosing statement containing the "break."

According to the Go Programming Language Specification:

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

Therefore, the "break" statement will exit the "switch" block, not the outer "for" loop.

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