Golang label breaks

Source: Internet
Author: User
Tags switch loop
This is a creation in Article, where the information may have evolved or changed.

When we are nesting for multiple layers, we sometimes need to jump out of all nested loops, so we can use the Go label breaks feature.

Let's look at an example code:

Package Main

Import (
"FMT"
)

Func Main () {
Fmt. Println ("1")

Exit:
For I: = 0; I < 9; i++ {
For j: = 0; J < 9; J + + {
If I+j > 15 {
Fmt. Print ("Exit")
Break Exit
}
}
}

Fmt. Println ("3")
}

Execution effect:

Attention

    • The label is written at the beginning of the for loop and not at the end. And Goto are not the same. Although it is a direct break exit to the specified location.

The difference between a break's label and a goto label can be found in the following code:

Jloop:
For I: = 0; I < 10; i++ {
Fmt. Println ("Label i is", i)
For j: = 0; J < 10; J + + {
If J > 5 {
Jumped out of the way, but it's not going to come in this for loop anymore.
Break Jloop
}
}
}

Jump Statement goto statement can jump to a label within this function
Gotocount: = 0
Gotolabel:
gotocount++
If Gotocount < 10 {
Goto Gotolabel//If it is less than 10, jump to Gotolabel
}

The Break tab can jump out of a for loop, and can also jump out of a select switch loop, referring to the following code:

L
for; Count < 8192; count++ {
Select {
Case e: = <-self.pidch:
Args[count] = E

Default
Break L//Jump out of select and for loop
}

}

Reference:

Go ' s block and identifiers scope
http://studygolang.com/articles/1438

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.