【Go】Basic syntax-control structures

Control structures are ubiquitous in programming languages, they control the flow

Compared with other programming languages, the control structure in go is less, there is no loop like do and while

There is a special select in go

The control structure of go does not need parentheses, but the statement must be in curly brackets. Similarly, the left curly bracket must be on the same line as the judgment statement.

if structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
    "fmt"
)

func main() {
    var age int = 29

    if age> 30 {
        fmt.Println("30 standing")
    } else {
        fmt.Println("You are still too young!")
    }
}
``

Save as helloworld.go, then execute

```go
[me@VM_0_14_centos go] # go run helloworld.go
You are still too young!

for loop structure

The for loop is composed of three parts, which are separated by semicolons;

Initialization statement: executed before the first iteration
Conditional expression: each evaluation of the iterator
Post statement: executed at the end of each iteration

Look at a simple program that sums 1 to 100:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
   "fmt"
)

func main () {
   var sum int = 0

   for i: = 1; i <= 100; i ++ {
       sum + = i
   }

   fmt.Println (sum)
}

Save as helloworld.go, then execute

1
2
[me@VM_0_14_centos go] # go run helloworld.go
5050

Here is a shortcut for variable definition: =, used in loop structure, concise and convenient

breank, continue terminate loop structure

These two have basically the same semantics as other programming languages

range

range is generally used for loops, it is an iterator

1
2
3
4
5
6
7
8
9
10
11
12
pakcage main
import (
    "fmt"
)

func main() {
    list: = []string {"a", "b", "c", "d", "e", "f"}

    for k, v: = range list {
        fmt.Printf("% d% s \n", k, v)
    }
}

Save as hello.world.go, and execute the result:

1
2
3
4
5
6
7
[me@VM_0_14_centos go] # go run helloworld.go
0 a
1 b
2 c
3 d
4 e
5 f

So range is actually an iterator, iterating over the loop, and returning a sequence number of key and a value of value

switch

Go’s switch is more flexible. Expressions can be non-constant or integer, even without expressions.

If there is no expression, it matches true by default

1
2
3
4
5
switch i {
    case 0:
    case 1:
        test()
}

When i == 0 matches, it does not call test () by default.

1
2
3
4
5
switch i {
    case 0: fallthrough
    case 1:
        test ()
}

At this time, when i == 0 matches, test () is called

Persist in original technology sharing, your support will encourage me to continue to create!