Go language learning record (2)

1. Go language conditional statement

Like C++, Go language provides several conditional judgment statements: if statement, if...else statement, if nested statement, switch statement. The function of the above statement is the same as that of C++, and a new select statement is also provided.

if statement

The syntax of if statement in Go programming language is as follows −

if 布尔表达式 {
   /* 在布尔表达式为 true 时执行 */
}

The writing method is basically the same as C++, and special attention should be paid to the fact that the curly braces cannot stand alone .

if...else statement

The syntax of if...else statement in Go programming language is as follows −

if 布尔表达式 {
   /* 在布尔表达式为 true 时执行 */
} else {
  /* 在布尔表达式为 false 时执行 */
}

Also pay attention to the curly braces~

if nested statement

The syntax of if nested statement in Go programming language is as follows:

if 布尔表达式 1 {
   /* 在布尔表达式 1 为 true 时执行 */
   if 布尔表达式 2 {
      /* 在布尔表达式 2 为 true 时执行 */
   }
}

switch statement

The syntax of switch statement in Go programming language is as follows −

switch var1 {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

It should be noted that the execution process of the switch statement is from top to bottom until a matching item is found, and there is no need to add a break after the matching item, because the switch has a break statement at the end of the case by default, and other cases will not be executed after the match is successful. case, this is different from C++ , if we need to execute the following case, we can use fallthrough.

Example:

package main

import "fmt"

func main() {
   /* 定义局部变量 */
   var grade string = "B"
   var marks int = 90

   switch marks {
      case 90: grade = "A"
      case 80: grade = "B"
      case 50,60,70 : grade = "C"
      default: grade = "D"  
   }

   switch {
      case grade == "A" :
         fmt.Printf("优秀!\n" )    
      case grade == "B", grade == "C" :
         fmt.Printf("良好\n" )      
      case grade == "D" :
         fmt.Printf("及格\n" )      
      case grade == "F":
         fmt.Printf("不及格\n" )
      default:
         fmt.Printf("差\n" );
   }
   fmt.Printf("你的等级是 %s\n", grade );      
}

The above code execution result is:

Excellent! 
Your grade is A

The switch statement can also be used in type-switch to determine the variable type actually stored in an interface variable . This is a function that C++ switch does not have.

The syntax format of Type Switch is as follows:

switch x.(type){
    case type:
       statement(s);      
    case type:
       statement(s); 
    /* 你可以定义任意个数的case */
    default: /* 可选 */
       statement(s);
}

Example:

package main

import "fmt"

func main() {
   var x interface{}
     
   switch i := x.(type) {
      case nil:  
         fmt.Printf(" x 的类型 :%T",i)                
      case int:  
         fmt.Printf("x 是 int 型")                      
      case float64:
         fmt.Printf("x 是 float64 型")          
      case func(int) float64:
         fmt.Printf("x 是 func(int) 型")                      
      case bool, string:
         fmt.Printf("x 是 bool 或 string 型" )      
      default:
         fmt.Printf("未知型")    
   }  
}

The above code execution result is:

type of x: <nil>

Using fallthrough will force the execution of the following case statement, and fallthrough will not judge whether the expression result of the next case is true.

package main

import "fmt"

func main() {

    switch {
    case false:
            fmt.Println("1、case 条件语句为 false")
            fallthrough
    case true:
            fmt.Println("2、case 条件语句为 true")
            fallthrough
    case false:
            fmt.Println("3、case 条件语句为 false")
            fallthrough
    case true:
            fmt.Println("4、case 条件语句为 true")
    case false:
            fmt.Println("5、case 条件语句为 false")
            fallthrough
    default:
            fmt.Println("6、默认 case")
    }
}

The above code execution result is:

2. The case conditional statement is true 
3. The case conditional statement is false 
4. The case conditional statement is true

From the output of the above code, it can be seen that the switch starts to execute from the first case whose judgment expression is true. If the case has fallthrough, the program will continue to execute the next case, and it will not judge the expression of the next case. Whether the formula is true.

select statement

The syntax of the select statement in the Go programming language is as follows:

select {
    case communication clause  :
       statement(s);      
    case communication clause  :
       statement(s);
    /* 你可以定义任意数量的 case */
    default : /* 可选 */
       statement(s);
}

The syntax of the select statement is described below:

  • Each case must be a communication
  • All channel expressions are evaluated
  • All expressions sent will be evaluated
  • If any communication is possible, it is performed, the others are ignored.
  • If there are multiple cases that can be run, Select will randomly and fairly select one for execution. Others will not execute.
    otherwise:
    1. If there is a default clause, the statement is executed.
    2. Without a default clause, select blocks until some communication can run; Go does not re-evaluate channels or values.

Select statement application demo:

package main

import "fmt"

func main() {
   var c1, c2, c3 chan int
   var i1, i2 int
   select {
      case i1 = <-c1:
         fmt.Printf("received ", i1, " from c1\n")
      case c2 <- i2:
         fmt.Printf("sent ", i2, " to c2\n")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            fmt.Printf("received ", i3, " from c3\n")
         } else {
            fmt.Printf("c3 is closed\n")
         }
      default:
         fmt.Printf("no communication\n")
   }    
}

The above code execution result is:

no communication

This code involves the knowledge of Go concurrency, which has not been learned here, so for the time being, select is understood as a special switch statement for judging communication, and the execution process is shown in the above syntax.

2. Go language loop statement

There are 3 forms of For loop in Go language, only one of them uses semicolon.

Same as C++'s for :

for init; condition; post { }

Same as C++'s while :

for condition { }

Same as for(;;) in C++ :

for { }
  • init: Generally, it is an assignment expression, which assigns an initial value to the control variable;
  • condition: relational expression or logical expression, loop control condition;
  • post: Generally, it is an assignment expression, which increments or decrements the control variable.

The range format of the for loop can iterate over slices, maps, arrays, strings, etc. The format is as follows:

for key, value := range oldMap {
    newMap[key] = value
}

The key and value in the above code can be omitted.

If you only want to read the key, the format is as follows:

for key := range oldMap
//或者:
for key, _ := range oldMap

If you only want to read the value, the format is as follows:

for _, value := range oldMap

Example:

package main
import "fmt"

func main() {
    map1 := make(map[int]float32)
    map1[1] = 1.0
    map1[2] = 2.0
    map1[3] = 3.0
    map1[4] = 4.0
   
    // 读取 key 和 value
    for key, value := range map1 {
      fmt.Printf("key is: %d - value is: %f\n", key, value)
    }

    // 读取 key
    for key := range map1 {
      fmt.Printf("key is: %d\n", key)
    }

    // 读取 value
    for _, value := range map1 {
      fmt.Printf("value is: %f\n", value)
    }
}

The output of the operation is:

key is: 4 - value is: 4.000000
key is: 1 - value is: 1.000000
key is: 2 - value is: 2.000000
key is: 3 - value is: 3.000000
key is: 1
key is: 2
key is: 3
key is: 4
value is: 1.000000
value is: 2.000000
value is: 3.000000
value is: 4.000000

The range format of the for loop is actually to traverse a container and operate in the loop body. Its specific usage is explained in the chapter of Go language range. Here we mainly understand the grammatical format of the for statement.

It can be seen that in the case of the same for statement, the Go language is almost only two parentheses () less than C++, and the writing method is basically the same. The assignment statement and the loop control condition are also separated by a semicolon. For the while statement of C++, for is still used in the Go language, but there is basically only this difference.

The loop nested statement will not be recorded, and the writing method is the same as if nested. Go's loop control statements are also break, continue, and goto . These three statements can use tags to jump to the statement you want to execute. Take break as an example:

package main

import "fmt"

func main() {

   // 不使用标记
   fmt.Println("---- break ----")
   for i := 1; i <= 3; i++ {
      fmt.Printf("i: %d\n", i)
      for i2 := 11; i2 <= 13; i2++ {
         fmt.Printf("i2: %d\n", i2)
         break
      }
   }

   // 使用标记
   fmt.Println("---- break label ----")
   re:
      for i := 1; i <= 3; i++ {
         fmt.Printf("i: %d\n", i)
         for i2 := 11; i2 <= 13; i2++ {
         fmt.Printf("i2: %d\n", i2)
         break re
      }
   }
}

The execution result is:

---- break ----
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11
---- break label ----
i: 1
i2: 11   

3. Go language function

function definition

The format of Go language function definition is as follows:

func function_name( [parameter list] ) [return_types] {
   函数体
}

Function definition analysis:

  • func: The function is declared from func (different from C++ from the return value type)
  • function_name: The function name, parameter list and return value type form the function signature.
  • parameter list: The parameter list, the parameter is like a placeholder, when the function is called, you can pass the value to the parameter, this value is called the actual parameter. The parameter list specifies the parameter type, order, and number of parameters. Parameters are optional, which means that functions can also contain no parameters.
  • return_types: return type, the function returns a list of values. return_types are the data types of the column values. Some functions do not need to return a value, in which case return_types is not necessary. (The return value type is written after the parameter list)
  • Function body: the collection of code defined by the function.

The following example is the code of the max() function, which passes in two integer parameters num1 and num2 and returns the maximum value of these two parameters:

/* 函数返回两个数的最大值 */
func max(num1, num2 int) int {
   /* 声明局部变量 */
   var result int

   if (num1 > num2) {
      result = num1
   } else {
      result = num2
   }
   return result
}

The function calling method is the same as C++ , so it is not recorded. Here is the function of returning multiple values.

Go functions can return multiple values, for example:

package main

import "fmt"

func swap(x, y string) (string, string) {
   return y, x
}

func main() {
   a, b := swap("Google", "Runoob")
   fmt.Println(a, b)
}

The execution result is:

Runoob Google

Functions that return multiple values ​​are functions that C++ does not have, and C++ functions have only one return value.

The transfer of function parameters also has two types of value transfer and reference transfer , the effect is the same as C++, and it will not be recorded here.

The Go language variable scope rules are the same as C++ and are not recorded.

4. Go language array

declare array

The array declaration in Go language needs to specify the element type and the number of elements. The syntax format is as follows:

var variable_name [SIZE] variable_type

The above is the definition of a one-dimensional array. For example, the following defines the array balance with a length of 10 and a type of float32:

var balance [10] float32

Initialize the array

The following demonstrates array initialization:

var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
//或者
balance := [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}

If the length of the array is uncertain, you can use ... instead of the length of the array, and the compiler will infer the length of the array by itself based on the number of elements:

var balance = [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
或
balance := [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0}

If the length of the array is set, we can also initialize elements by specifying subscripts:

//  将索引为 1 和 3 的元素初始化
balance := [5]float32{1:2.0,3:7.0}

This initialization function of specifying the subscript is not available in C++. To initialize some elements of the array in C++, you can only assign values ​​to the first few digits of the array at the time of declaration, and you cannot specify the subscript assignment like this.

access array elements

Array elements can be read by index (position). The format is to add square brackets after the array name, and the value of the index is in the square brackets. For example:

var salary float32 = balance[9]

Multidimensional arrays and passing arrays to functions are the same as C++ and are not documented.

5. Go language pointer

pointer declaration

var var_name *var-type

var-type is the pointer type, var_name is the pointer variable name, and * is used to specify that the variable is a pointer. The following are valid pointer declarations:

var ip *int        /* 指向整型*/
var fp *float32    /* 指向浮点型 */

Add the * sign (prefix) in front of the pointer type to get the content pointed to by the pointer (same as C++).

package main

import "fmt"

func main() {
   var a int= 20   /* 声明实际变量 */
   var ip *int        /* 声明指针变量 */

   ip = &a  /* 指针变量的存储地址 */

   fmt.Printf("a 变量的地址是: %x\n", &a  )

   /* 指针变量的存储地址 */
   fmt.Printf("ip 变量储存的指针地址: %x\n", ip )

   /* 使用指针访问值 */
   fmt.Printf("*ip 变量的值: %d\n", *ip )
}

The execution output is:

a 变量的地址是: 20818a220
ip 变量储存的指针地址: 20818a220
*ip 变量的值: 20

Go null pointer

When a pointer is defined and not assigned to any variable, its value is nil.

A nil pointer is also known as a null pointer.

Conceptually, nil is the same as null, None, nil, and NULL in other languages, and they all refer to zero or empty values.

A pointer variable is often abbreviated as ptr.

package main

import "fmt"

func main() {
   var  ptr *int

   fmt.Printf("ptr 的值为 : %x\n", ptr  )
}

The output is:

The value of ptr is: 0

Null pointer judgment:

if(ptr != nil)     /* ptr 不是空指针 */
if(ptr == nil)    /* ptr 是空指针 */

In fact, pointers in Go language are not different from C++ except for the difference in writing. Operations such as the use of pointers, pointer arrays, multi-level pointers, and pointers as function parameters are the same as C++, so they are not recorded.

6. Summary

The learning records in Chapter 2 include conditional statements, loop statements, functions, arrays, and pointers. Each part is roughly the same as C++, but there are also some functions that C++ does not have, such as select statements, for loop range formats, and function returns. value, initialize the array to specify subscript elements, etc.

Guess you like

Origin blog.csdn.net/qq_43824745/article/details/126246164