Go Basics - operators, process control

Go Basics - Contents

(1) Go start
(2) Variable
(3) Operators, process control

1, Operator

priorityclassificationoperatorAssociativity
1Comma Operator ,From left to right
2Assignment Operators = += -= *= /= %= >= <<= &= ^= |=Right to left
3Logical or||From left to right
4Logic and&&From left to right
5Bitwise OR|From left to right
6Bitwise XOR^From left to right
7Bitwise AND&From left to right
8Equal / unequal== !=From left to right
9Relational operator< <= > >=From left to right
10Shift Bitwise Operators << >>From left to right
11Addition / subtraction+ -From left to right
12Multiplication / division / remainder*(multiplication sign) /%From left to right
13unary operator ! * (pointer) & + + -- + (exactly) - (minus sign)Right to left
14postfix operator () [] ->From left to right

Note: the higher the priority value, the higher the priority

2, Conditional statement

2.1 basic writing method

if condition {
	// do something
} else if confition2 {
	// do something
} else {
	// do something
}

2.2 special writing

If also has a special writing method. You can add an execution statement before the if expression, and then judge according to the variable value. The code is as follows:

if err := Connect(); err != nil {
    fmt.Println(err)
    return
}

Connect is a function with a return value. err:=Connect() is a statement. After connect is executed, the error is saved to the err variable.

err != nil is the judgment expression of if. When err is not empty, an error is printed and returned.

In this way, the return value and judgment can be processed on one line, and the scope of the return value is limited to the combination of if and else statements.

In programming, the smaller the scope of variables, the less likely the problems will be caused. Each variable represents a state. Where there is a state, the state will be modified. The local variables of a function will only affect the execution of a function, but the global variables may affect the execution state of all codes, Therefore, limiting the scope of variables is of great help to the stability of the code.

3, Loop statement for

Loop statements in the Go language only support the for keyword

3.1 basic writing method

sum := 0
for i := 0; i < 10; i++ {
    sum += i
}

3.2 infinite cycle

sum := 0
for {
    sum++
    if sum > 100 {
        break
    }
}

3.3 initial statement in for (statement executed when starting the loop)

The initial statement is the statement executed before the first loop. Generally, the initial statement is used to initialize the variable. If the variable is declared here, its scope will be limited to the scope of this for.

step := 2
for ; step > 0; step-- {
    fmt.Println(step)
}

3.4 conditional expression in for (switch controlling whether to cycle)

var i int
for ; ; i++ {
    if i > 10 {
        break
    }
}
var i int
for {
    if i > 10 {
        break
    }
    i++
}
var i int
for i <= 10 {
    i++
}

End statement in 3.5 for (statement executed at the end of each loop)

If the loop is forcibly exited by break, goto, return, panic and other statements before ending each loop, the ending statement will not be executed.

4, Key value loop for range

4.1 basic writing method

for range structure is a unique iterative structure of Go language, which is very useful in many cases. for range can traverse arrays, slices, strings, map s and channel s. for range syntax is similar to foreach statements in other languages. The general form is:

for key, val := range coll {
    ...
}

The return value traversed by for range has certain rules:

  • Array, slice, string return index and value.
  • map returns keys and values.
  • Channel returns only the values within the channel.

4.2 traversing arrays and slices (obtaining indexes and values)

for key, value := range []int{1, 2, 3, 4} {
    fmt.Printf("key:%d  value:%d\n", key, value)
}

4.3 traversal string (get characters)

var str = "hello Hello"
for key, value := range str {
    fmt.Printf("key:%d value:0x%x\n", key, value)
}

4.4 traversing the map (obtaining the key and value of the map)

m := map[string]int{
    "hello": 100,
    "world": 200,
}
for key, value := range m {
    fmt.Println(key, value)
}

4.5 traversing channel (receiving channel data)

c := make(chan int)
go func() {
    c <- 1
    c <- 2
    c <- 3
    close(c)
}()
for v := range c {
    fmt.Println(v)
}

4.6 select the desired variable in traversal

m := map[string]int{
    "hello": 100,
    "world": 200,
}
for _, value := range m {
    fmt.Println(value)
}

5, Switch case

5.1 basic writing method

var a = "hello"
switch a {
case "hello":
    fmt.Println(1)
case "world":
    fmt.Println(2)
default:
    fmt.Println(0)
}

be careful:

  • It supports one branch and multiple values, and different case expressions are separated by commas
  • Branch expressions are supported. In this case, switch does not need to be followed by judgment variables
var a = "mum"
switch a {
case "mum", "daddy":
    fmt.Println("family")
}

var r int = 11
switch {
case r > 10 && r < 20:
    fmt.Println(r)
}

5.2 fallthrough across case

In Go language, case is an independent code block. After execution, the next case will not be executed immediately as in C language. However, in order to be compatible with some transplanted codes, the fallthrough keyword is added to realize this function. The code is as follows:

var s = "hello"
switch {
case s == "hello":
    fmt.Println("hello")
    fallthrough
case s != "world":
    fmt.Println("world")
}

be careful:

  • fallthrough is not recommended for newly written code

6, goto

6.1 using goto to exit a multi-layer loop

6.2 centralized processing of errors using goto

Keywords: Go

Added by frontlines on Mon, 25 Oct 2021 07:02:18 +0300