Home > Backend Development > Golang > Does `break` Exit a `for` Loop or Just a `switch` Statement in Go?

Does `break` Exit a `for` Loop or Just a `switch` Statement in Go?

Susan Sarandon
Release: 2024-12-31 06:02:14
Original
576 people have browsed it

Does `break` Exit a `for` Loop or Just a `switch` Statement in Go?

Switch/Select Statement Termination with Break

While switch and select statements typically end automatically at the end of each case, it's worth considering the effect of an explicit break statement within these blocks. Let's take a particular code snippet as an example:

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

The question arises: does the break statement break from the outer for loop or only the switch block?

To answer this, we refer to the Go Programming Language Specification on Break Statements:

"A 'break' statement terminates execution of the innermost 'for', 'switch' or 'select' statement. If there is a label, it must be that of an enclosing 'for', 'switch' or 'select' statement, and that is the one whose execution terminates."

In our case, since no label is provided, the break statement will terminate the innermost statement, which is the switch block. Therefore, the break statement will not exit the outer for loop, but only cease execution of the switch statement, allowing the program to continue with the next iteration of the loop.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template