A Tour of Go:basics 2

Source: Internet
Author: User

For

The For statement consists of three basic parts, separated by semicolons:

    • Initial statement: Executes only before the start of the first loop, usually the variable definition and initialization, where the variables defined are scoped only to the for loop itself.
    • Conditional expression: Every time the loop starts before it executes, when false ends the loop.
    • Post statement: Executed at the end of each iteration.

Skills:

    • The initial statement and the post statement can be omitted.
    • Conditional expressions can also be omitted, which is a dead loop.
    • The go language has only one loop structure, which is the for statement. The while statement is also represented by a for in go.
// forsum := 1for ; sum < 1000; {    sum += sum}// whilesum := 1for sum < 1000 {    sum += sum}

Note the point:

    • Unlike other languages, three statements do not need to be enclosed in parentheses.
    • The loop body needs to be enclosed in curly braces.
If

As with for, the IF statement can contain an initial statement scoped to the if itself (including else). Similarly, if statements do not require parentheses, but curly braces are required.

Switch

Switch is a better choice for if else statements in some scenarios. Match to a case equal to condition and execute, and then stop switch without an explicit break.
You can also have an initial statement.
The condition can be null, which indicates switch true.

Defer

Postpone execution until the surrounding functions are executed.
The deferred function is placed in the stack, so it follows the LIFO principle.
Application scenarios such as for cleaning actions, see: Https://blog.golang.org/defer-panic-and-recover

A Tour of Go:basics 2

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.