Go basic series: Process Control Structure

Source: Internet
Author: User
Tags switch case

Condition judgment structure: If else
Branch selection structure: Switch case
Loop Structure:
Break: exit the for or switch structure (and select)
Continue: Enter the next for Iteration

Although go is a C-like language, the conditional expressions in these flow control statements do not use parentheses. Sometimes errors may occur when brackets are used, but some complicated condition judgments require brackets to change the priority.

For example:

if (name == "longshuai" && age > 23) || (name == "xiaofang" && age < 22) {    print("yeyeye!!!")}
If statement
if condition1 {    // do something} else if condition2 {    // do something else} else {    // catch-all or default}

Note that go has strict syntax requirements. Left braces{It must be in the same line as if, else, or else if, with the right braces}Line breaks are required. If else or else if exists, the two keywords must be followed. That is to say, in the above code structure, the positions of braces are mandatory and cannot be placed with line breaks.

In go, an initialization statement can be added before the condition of the IF statement. For example, it is common in go:

if val := 10; val > max {    // do something}

It is equivalent:

val := 10if val > max {    // do something}

However, note that in the abbreviated method,valThe scope is only within the if range, and the Val cannot be accessed outside the IF. If a Val has been defined before the if statement, the Val will be overwritten by the VAL in the IF statement and will not be restored until the if statement exits.

Func main () {VAL: = 20 if Val: = 10; Val> 3 {println ("true")} println (VAL) // output 20}

One solution is not to use the if initialization statement.:=, But directly use=But this will modify the original value.

Func main () {VAL: = 20 if Val = 10; Val> 3 {println ("true")} println (VAL) // output 10}

In go, two (or more) return values are often used. One return value is used as a value, the other as a Boolean value, or an error message. The IF statement is usually used to check whether the function with multiple returned values is successful.

Note that there are two types of returned values: OK and err. The former is a Boolean value, and the latter is a string indicating the error message. If there is no error, the err is nil.

Value, OK: = func_name () If! OK {// func_name execution error OS. Exit (1)} value, err: = func_name () If Err! = Nil {// func_name execution error OS. Exit (1) // or return err}

To get a more common judgment method:

If value, OK: = func_name (); OK {// OK is true, function execution is successful} else {// OK is false, function execution fails OS. exit (1)} If value, err: = func_name (); Err! = Nil {// If err is not nil, return err // or OS. Exit (1)} else {// err is null, indicating that the execution is correct}
Switch statement

The switch statement is used to provide branch tests. There are two Swithc structures: expression switch and type switch. This article only introduces expression switch, which is used to determine whether the expression is true.

Expression switch also has three forms: equivalent comparison, expression comparison, and initialization expression.

Equivalent comparison Structure: When the value of var1 is val1, execute statement1. When the value of var1 is val2, execute statement2, if none of them meet, execute the default statement.

switch var1 {    case val1:        statement1    case val2:        statement2    default:        statement}

The equivalence is quite limited. Only the values in var1 and case can be compared to whether they are equal. If you want to compare, or other expression types, you can use the following expression to compare the structure.

Expression comparison Structure: Evaluate the condition in each case structure. If the evaluation is true, execute the statement and exit (by default ).

switch {    case condition1:        statement1    case condition2:        statement2    default:        statement}

Initialization expression: The initialization expression can be added to the switch like if, and the same scope is only visible to the switch. Note that the end of initialization is. See the following example.

Switch initialization; {// do not omit the semicolon case condition1: statement1 case condition2: statement2 defautl: Statement}

defaultIt is optional and can be written in any position of the switch.

If there are multiple statements to be executed in case, you can increase the brackets or not. When there is only one statement, statement can be in the same line as case.

Multiple values can be provided for testing in case. They are separated by commas (,). Each value meets the following conditions:

switch var1 {    case val1,val2,val3:        statement1    case val4,val5:         statement2    default:        statement}

For example:

VAL: = 20 switch Val {case 10, 11, 15: println (11, 15) case 16, 20, 22: // hit println (16, 20, 22) default: println ("nothing ")}

Even if the expression compares the structure, you can use commas to separate multiple expressions. In this case, it is equivalent to using logic or "|:

Func main () {VAL: = 21 switch {case Val % 4 = 0: println (0) case Val % 4 = 1, Val % 4 = 2: // hit println (1, 2) Default: println ("3 ")}}

By default, case hit ends, so only one of all cases will be executed. If you want to execute multiple statements, you can addfallthroughIt will jump directly to the next case and execute it unconditionally. If there is fallthrough in the next case, the same logic will be applied. In addition, fallthrough must be followed by only the next case or default. It cannot be any additional statement. Otherwise, an error is reported.

For example:

Func main () {VAL: = 21 switch Val % 4 {Case 0: println (0) Case 1, 2: // hit println (1, 2) // output fallthrough // execute the next one without conditional evaluation // println ("SD") // This statement cannot be added case 3: println (3) // output fallthrough // execute the next one without conditional evaluation default: println ("end") // output }}

The execution result is:

1 23end

fallthroughIt is generally used to skip a case. For example:

swtich i {    case 0: fallthrough    case 1: statement1    default: statement}

It indicates that statement1 is executed when it is equal to 0 or 1. This is the same as the features of multiple ratings in the previous case.

The following is an example of a switch that initializes the expression structure:

Func main () {VAL: = 21 switch VAL: = 23; {case Val % 4 = 0: println (0, Val) case Val % 4 = 1 | Val % 4 = 2: println (1, 2, Val) Default: // hit println (3, Val) // output "3 23"} println (VAL) // Output 21}
For statement

There is only one loop structure in go:.

For
// Complete format forfor Init; condition; modif {} // For only conditional judgment, implement the while function // Add the exit condition in the loop body, otherwise, the infinite loop for condition {}

For example:

// Complete func main () {for I: = 0; I <5; I ++ {FMT. println (I) }}// only the conditional format func main () {var I Int = 5 for I> = 0 {I = I-1 FMT. printf (I )}}
Infinite Loop

There are several ways to implement an infinite loop of. As long as the for condition judgment part is omitted, an infinite loop can be achieved.

for i := 0;;i++ for { } for ;; { }for true { }

In an infinite loop, exit statements, such as break, OS. Exit, and return, are usually added to the loop body.

For range Traversal

The range keyword is very useful and can be used to iterate those iteratable objects. For example, slice, map, and array can also iterate strings or even Unicode strings.

for index,value := range XXX {}

Note that value is a copy copied from XXX, so modifying the value in XXX through value is invalid. in the loop body, value should always be used as a read-only variable. If you want to modify the value in XXX, you should use index to modify the source value (different types of modifications are modified in different ways ).

Take the iteration string as an example.

Func main () {var A = "xiaofang, hello" for index, value: = range A {println (index, string (value ))}}

Output result:

0x1 I2 A3 O4 F5 A6 N7 G8, 9 hello!

It can be seen that during string iteration, the index is based on characters rather than bytes.

Modifying slice through value below will be invalid.

Func main () {S1: = [] int {11, 22, 33} for index, value: = range S1 {value + = 1 // valid only in the for structure. println (index, value)} FMT. the result of println (S1) // For is still [11 22 33]}.

To modify the slice in the loop structure, you should use the index method:

func main() {    s1 := []int{11,22,33}    for index,value := range s1 {        value += 1        s1[index] = value        fmt.Println(index,value)    }    fmt.Println(s1)   // [12 23 34]}
Break and continue

Breake is used to exit the entire loop. If it is a nested loop, exit the loop where it is located. In addition to the for loop, break can also be used in the switch or select structure.

Continue is used to exit the current iteration and enter the next iteration. Continue can only be used in a for loop.

Tag and goto

When the first word in a row is followed by a colon, go considers it a label. For example:

func main() {LABEL1:    for i := 0; i <= 5; i++ {        for j := 0; j <= 5; j++ {            if j == 4 {                continue LABEL1            }            fmt.Printf("i is: %d, and j is: %d\n", i, j)        }    }}

Tags can be used to redirect break, continue, and goto to the specified position for further execution. For examplecontinue LABEL1, Whenj == 4And then directly jump to the outer loop to enter the next iteration. Whilebreak LABELThen, exit the loop of the label.

Goto is too lazy to introduce it. No one is using it anyway, and it is strongly recommended not to use it, or even not to use tags. Generally, the structure of label or goto can be rewritten to other better statements.

Go basic series: Process Control Structure

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.