GoLang language learning record

Posted by keystroke on Sat, 18 Dec 2021 23:26:18 +0100

createdtime 20210827

updatedtime 20210827

author venki.chen

abstract

Focus on learning basic knowledge (data type, control structure and precautions)

data type

  1. Define structure
package api

import (
	"fmt"
)

// Teacher definition structure
type Teacher struct {
	Name   string
	Age    int
	School string
}

// AccessApiOne entrance
func AccessApiOne() {
	// Create structure method 1
	var t1 Teacher
	t1.Name = "venki.chen"
	t1.Age = 28
	t1.School = "Guangxi University of science and technology"
	fmt.Println(t1)
	fmt.Println("----------------------")

	// Structure creation method 2
	var t2 Teacher = Teacher{}
	t2.Name = "cwxc"
	t2.Age = 28
	t2.School = "Guangxi University of science and technology"
	fmt.Println(t2)
	fmt.Println("--------------------------")

	// Create structure method 3 return structure pointer
	var t3 *Teacher = new(Teacher)
	/*(*t3).Name = "slp"
	(*t3).Age = 26
	(*t3).School = "Fujian Normal University“*/
	/*The reason is (* T3) Name and T3 Name can be used with each other because the go bottom layer has carried out value operation on this definition, and T3 Name is converted to (* T3) Name*/
	t3.Name = "slp"
	t3.Age = 18
	t3.School = "Fujian Normal University"
	fmt.Println(*t3)
	fmt.Println("--------------------------")

	// Create structure mode 4 return structure pointer
	var t4 *Teacher = &Teacher{}
	/*(*t4).Name = "slp"
	(*t4).Age = 26
	(*t4).School = "Fujian Normal University“*/
	/*The reason is (* T4) Name and T4 Name can be used mutually because the bottom layer of go has carried out value operation on this definition, and T4 Name is converted to (* T4) Name*/
	t4.Name = "slp"
	t4.Age = 26
	t4.School = "Fujian Normal University"
	fmt.Println(*t4)
	fmt.Println("--------------------------")
}
  1. Define map
func MapMain() {
	// Define map mode 1
	var a map[int]string = make(map[int]string)
	a[2021082601] = "Chen"
	a[2021082602] = "writing"
	a[2021082603] = "Small"
	a[2021082604] = "exceed"
	a[2021082605] = "stone"
	a[2021082606] = "Li"
	a[2021082606] = "win"
	a[2021082607] = "flat"
	fmt.Println(a)
	fmt.Println("-----------------")
	
	// Define map mode 2
	b := make(map[int]string)
	b[2021] = "1"
	b[2022] = "2"
	fmt.Println(b)
	fmt.Println("-----------")
	
	// Define map mode 3
	c := map[int]string{
		202106: "Small",
		202107: "exceed",
	}
	fmt.Println(c)
	fmt.Println("--------")
	map1 := make(map[string]map[int]string)
	// assignment
	map1["Class 1"] = make(map[int]string)
	map1["Class 1"][2021082601] = "Chen Chen 1"
	map1["Class 1"][2021082602] = "Wen Wen 1"
	map1["Class 1"][2021082603] = "Little 1"
	map1["Class 1"][2021082604] = "Super super 1"

	map1["Class 2"] = make(map[int]string)
	map1["Class 2"][2021082601] = "Chen Chen 2"
	map1["Class 2"][2021082602] = "Wen Wen 2"
	map1["Class 2"][2021082603] = "Little 2"
	map1["Class 2"][2021082604] = "Super super 2"
	for k1, v1 := range map1 {
		for k2, v2 := range v1 {
			fmt.Printf("The total number of classes is:%v,The class is:%v,Total students:%v individual,They are: Name:%v,
			Student number:%v Students\n", len(map1), k1, len(v1), v2, k2)
		}
	}

	fmt.Println("--------------")
	accountedInvoiceAfId := make([]int, 0)
	fmt.Printf("The length of the slice is:%v,Capacity:%v\n", len(accountedInvoiceAfId), 
	cap(accountedInvoiceAfId))
}
  1. Define slice
func sliceMain() {
	// array
	var intarr [6]int = [6]int{3, 6, 9, 1, 4, 7}
	fmt.Println(intarr)

	// section
	slice := intarr[1:3]
	fmt.Println(slice)
	fmt.Printf("slice Number of elements:%v\n", len(slice))
	fmt.Printf("slice The capacity is:%v\n", cap(slice))
	fmt.Println("----------")
	fmt.Printf("The address of the element with subscript 1 in the array is:%p\n", &intarr[1])
	fmt.Printf("The address of the element with subscript 0 in the slice is:%p\n", &slice[0])
	fmt.Println("----------")
	slice[0] = 16
	fmt.Println(intarr)
	fmt.Println(slice)
	fmt.Println("----------")

	// Create slice
	slice1 := make([]int, 4, 20)
	fmt.Println(slice1)
	fmt.Printf("The length of the slice is:%v\n", len(slice1))
	fmt.Printf("The capacity of the slice is:%v\n", cap(slice1))
	fmt.Println("----------")

	// Traversal slice
	var arr3 [6]int = [6]int{1, 2, 3, 4, 5, 6}
	slice2 := arr3[0:6]

	// Traversal mode 1
	for i := 0; i < len(slice2); i++ {
		fmt.Printf("Sliced section%v The first values are:%v\n", i+1, slice2[i])
	}

	fmt.Println("--------------")
	
	// Traversal mode 2
	for key, value := range slice2 {
		fmt.Printf("slice2[%v]=%v\n", key, value)
	}
	fmt.Println(slice2)
	slice2 = append(slice2, 88, 50)

	fmt.Println(slice2)
}
  1. Define array
func arrMain() {
	var arr [2][3]int16

	fmt.Println(arr)
	fmt.Println("---------------------------")

	// Array memory address
	fmt.Printf("arr The memory address of is:%p\n", &arr)
	fmt.Printf("arr[0]The memory address of is:%p\n", &arr[0])
	fmt.Printf("arr[0][0]The memory address of is:%p\n", &arr[0][0])
	fmt.Println("---------------------------")

	// Initialize array
	var arr1 [2][3]int = [2][3]int{{1, 2, 3}, {4, 5, 6}}
	fmt.Println(arr1)
	fmt.Println("---------------------------")

	// Variable array
	var arr2 [3][3]int = [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

	// Mode 1 traversal
	for i := 0; i < len(arr2); i++ {
		for j := 0; j < len(arr2[i]); j++ {
			fmt.Printf("2D array%v Layer%v The column elements are:%v\n", i+1, j+1, arr2[i][j])
		}
	}
	fmt.Println("---------------------------")

	// Mode 2 Presentation
	for key, value := range arr2 {
		for k, v := range value {
			fmt.Printf("2D array%v Layer%v The column elements are:%v\n", key+1, k+1, v)
		}
	}
}
  1. Basic data type
func main() {
	// String data type
	var s1 string = "Hello, full hug Golang"
	fmt.Println(s1)
	var s2 string = "abc"
	s2 = "def"
	fmt.Println(s2)
	var s3 string = "abcdef\\ghijklm"
	fmt.Println(s3)
	var s4 string = "abcdef" + "ghijklm"
	fmt.Println(s4)
	var s5 string = `if else elseif`
	fmt.Println(s5)

	// Default value of basic data type
	var a int
	var b float32
	var c float64
	var d bool
	var e string
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
	fmt.Println(d)
	fmt.Println(e)

	// Explicit conversion of data type
	var n1 int = 100
	var n2 float32 = float32(n1)// The type of n1 remains unchanged
	fmt.Println(n1)
	fmt.Println(n2)
	fmt.Printf("%T",n1)
	fmt.Println()
	fmt.Printf("%T",n2)
	fmt.Println()
	var n3 int64 = 888888
	var n4 int8 = int8(n3)
	fmt.Println(n4)
	var venkiChen string = "venki.chen"
	fmt.Println(venkiChen)
}

control structure

  1. for loop
func forModule() {
	var i1 int = 1
	var i2 int = 2
	var i3 int = 3
	var i4 int = 4
	var i5 int = 5
	var sum int = 0
	sum += i1
	sum += i2
	sum += i3
	sum += i4
	sum += i5
	fmt.Printf("After summation:%v\n", sum)

	var sum int = 0
	var i int = 1
	i++
	sum += i
	sum += i
	sum += i
	sum += i
	sum += i
	fmt.Printf("After summation:%v,%i", sum, i)
	var sum int = 0
	for i := 1; i <= 5; i++ {
		sum += i
	}
	fmt.Printf("%v", sum)

	for {
		fmt.Println("Hello venki.chen")
	}
}
  1. switch branch
func branchModuleToSwitch() {
	var count int
	fmt.Println("Please enter your grade:")
	fmt.Scanln(&count)
	num := count / 10
	switch num {
	case 10, 11, 12:
		fmt.Printf("Your achievements are:%v,Rated as A level\n", count)
	case 9:
		fmt.Printf("Your achievements are:%v,Rated as B level\n", count)
		fallthrough
	case 8:
		fmt.Printf("Your achievements are:%v,Rated as C level\n", count)
	case 7:
		fmt.Printf("Your achievements are:%v,Rated as D level\n", count)
	case 6:
		fmt.Printf("Your achievements are:%v,Rated as E level\n", count)
	case 5:
		fmt.Printf("Your achievements are:%v,Rated as F level\n", count)
	case 4:
		fmt.Printf("Your achievements are:%v,Rated as G level\n", count)
	case 3:
		fmt.Printf("Your achievements are:%v,Rated as H level\n", count)
	case 2:
		fmt.Printf("Your achievements are:%v,Rated as I level\n", count)
	case 1:
		fmt.Printf("Your achievements are:%v,Rated as J level\n", count)
	case 0:
		fmt.Printf("Your achievements are:%v,Rated as K level\n", count)
	default:
		fmt.Printf("Your achievements are:%v,Rated as L level\n", count)
	}
}
  1. if branch
func branchModuleToIf() {
	var count int
	fmt.Println("Please enter the data you want to fill in:")
	fmt.Scanln(&count)
	if count < 30 {
		fmt.Printf("The number you entered is:%v Less than 30\n", count)
	} else {
		fmt.Printf("The number you entered is:%v Greater than 30\n", count)
	}

	if count >= 90 {
		fmt.Printf("Your grades are:%v,by A level\n", count)
	}
	if count >= 80 && count < 90 {
		fmt.Printf("Your grades are:%v,by B level\n", count)
	}
	if count >= 70 && count < 80 {
		fmt.Printf("Your grades are:%v,by C level\n", count)
	}
	if count >= 60 && count < 70 {
		fmt.Printf("Your grades are:%v,by D level\n", count)
	} else {
		fmt.Printf("Your grades are:%v,by E level\n", count)
	}

	if count >= 90 {
		fmt.Printf("Your grades are:%v,by A level\n", count)
	} else if count >= 80 {
		fmt.Printf("Your grades are:%v,by B level\n", count)
	} else if count >= 70 {
		fmt.Printf("Your grades are:%v,by C level\n", count)
	} else if count >= 60 {
		fmt.Printf("Your grades are:%v,by D level\n", count)
	} else {
		fmt.Printf("Your grades are:%v,by E level\n", count)
	}

	if count > 10 {
		fmt.Println("a")
	} else if count > 5 {
		fmt.Println("b")
	}
}

matters needing attention

  1. ++-- it can only be used alone and does not participate in the operation;
  2. Switch branch cannot declare variables with var, only with: =; Declaration;
  3. go language does not support function overloading (function names are the same and formal parameters are different);
  4. User defined data types are actually aliases for data types (but they must be the same when assigning values);
  5. The main function must be in the main package;
  6. Different files in the same package cannot declare duplicate name functions;
  7. Different file declarations under the same package may not be consistent with the folder name, but the package file declaration package name in the package file must be consistent;
  8. Execution order: (the init function in the import package is executed first) > global variable > init function > greater than main function;
  9. Closure: because a closure can retain a value of the last reference, it can be used repeatedly after being passed in once;
// GetSum defines a function. The return value type is function, and the formal parameters of this function are integer, and the return value is integer
func GetSum() func(int) int {
	var sum int = 0
	return func(num int) int {
		sum += num

		return sum
	}
}
  1. Defer keyword: when the defer keyword is encountered, the following code statements will be pushed into the stack, and the relevant values will be copied into the stack at the same time, which will not change with the changes behind the function. Application scenario: for example, if you want to close a used resource, you can directly defer when using it, Because defer has a delay mechanism (execute the statement that defer is pushed into the stack after the function is executed), it's easy to close it after you use it;
Add(30,60)
func Add(num int, num1 int) int {
	// In Golang, when the program encounters the defer keyword, it will not immediately execute the statement after defer, but press the statement after defer into a stack, and then continue to execute the code behind the function
	defer fmt.Println("num=", num)
	defer fmt.Println("num1=", num1)
	// Stack features first in and last out
	// After the function is executed, the statement is taken out of the stack and executed according to the first in first out rule
	var sum int = num + num1
	fmt.Println("sum=", sum)

	return sum
}
  1. After the slice is defined, it cannot be used directly (it is an empty []). It needs to reference an array or initialize the slice with make. The slice cannot cross the boundary;
  2. If map only declares that it has no assignment, it will not allocate memory space, but arr will not; The key and value of map are out of order; Key cannot be repeated. If repeated, the last value will replace the previous value; When making initializes the map, the second parameter can be omitted and a size is allocated by default;
  3. When initializing the structure, if the attribute contains pointer, slice and mapping, and no make is performed, then no space is allocated, and if no space is allocated, the assignment will report an error, so make must be performed at the same time of initialization;
  4. Structure time value type, different structures are independent of each other and are not affected;

Topics: Go