Home > Backend Development > Golang > How to break the outer loop within the inner loop

How to break the outer loop within the inner loop

WBOY
Release: 2024-02-09 10:12:29
forward
656 people have browsed it

How to break the outer loop within the inner loop

When writing complex nested loops, sometimes we need to break the outer loop in the inner loop to end the entire loop process early. However, in PHP, loop structures do not directly support this operation. Therefore, PHP editor Xigua will share with you some methods and techniques to achieve the need to break the outer loop in the inner loop. Whether it is using labels and goto statements, or using auxiliary variables and conditional judgments, this article will provide you with a comprehensive solution. Come and take a look!

Question content

for i := 0; i < 5; i++ {
        fmt.Println("i is", i)
        for j := 0; j < 3; j++ {
            if j == 2 {
                break
            }
            fmt.Println("j is ", j)
        }
    }
Copy after login

I want this code to interrupt the program if i equals 2. How do I signal that I want to interrupt the outer loop within the inner loop?

I don’t know how to interrupt or continue the outer loop

Solution

outerLoop:
    for i := 0; i < 5; i++ {
        for j := 0; j < 3; j++ {
            if i == 3 {
                break outerLoop
            }
            fmt.Println(i, j)
        }
    }
Copy after login

This is the answer. You can use labels in go to reference different loops

The above is the detailed content of How to break the outer loop within the inner loop. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template