Summary of basic knowledge of Golang language
1.go language has two types:
- Value type: numeric type, bool, string, array, struct structure
Variables store values directly. Memory is usually allocated in the stack. Modifying the value will not affect the source object - Reference types: pointer, slice, pipe, chan, map, interface
The variable stores an address, and the space corresponding to this address really stores data values. Memory is usually allocated on the heap. When no variable references this address, the data space corresponding to this address becomes garbage and is recycled by GC. At the same time, when the data value specified by the address changes, it will have an impact on the source object.
2. Definition of variables:
local variable
var `Variable name` `type` = `parameter` var `Variable name` = `parameter` `Variable name` := `parameter`
global variable
var ( `Variable name` = `parameter` )
Integer type: int8, int16, int32, Int64, run, byte, uint8, uint16, uint32, Uint64
Decimal type: float32,float64
3. The difference between single quotation marks and double quotation marks in golang language:
'' is used to represent the character type
'' is used to represent a string type
4. String splicing format:
var str1 string = "123"+ "456"
5. Basic data type conversion:
Converting data types in go language requires explicit conversion
Convert float64 type to float32 type
var n1 float64 = 3.2 n2 := float32(n1)
6. Convert basic data type to string data type:
First: FMT Sprintf
num1 := 3 string1 := fmt.Sprintf("%d",num1)
The second: strconv package function
str1 := strconv.FormatInt(num1,10) #The first parameter is a variable, and the second parameter is the type of this variable. 2 is a binary number, and 10 is a decimal number. See the official document for details
The third one: strconv Itoa
str1 := strconv.Itoa(num1) #num1 is of type int
7. Convert string data type to basic data type:
var str1 string = "1" //bool b,_ := strConv.ParseBool(str1) //int b,_ := strConv.ParseInt(str1,10,0) //float b,_ := strConv.ParseFloat(str1,64)
8. Pointer:
Pointer variables store an address, and the space pointed to by this address is the value
A * in front indicates that ptr is a pointer
Use & to view the pointer value of num
Use & PTR to modify the value of num directly
num := 1 var ptr *int = &num &ptr = 2
9. Receive keyboard input statements:
var name string fmt.Scanln(&name) or fmt.Scanf("%s",&name)
10. Branch structure
In addition to our commonly used if else branch structure, I will focus on the switch branch structure here
swich expression { case Expression 1, expression 2, expression 3: Statement block fallthrough default: Statement block }
Expressions can be variables or functions
case is equivalent to if
When there are pairs of expressions, the expressions are connected by or
default first and else
You can write nothing behind swtch
fallthrough is a swich penetration. By default, it penetrates one layer, which is equivalent to that other qualified statement blocks can be executed after meeting their conditions.
11.for cycle control
1. num1 := 10 for i:=0; i<num1;i++{ Statement block } 2. num1 := 10 i := 1 for i<num1{ Statement block i++ } 3. for { Statement block break }
If nothing is written after for, it is equivalent to an infinite loop
12. Traversal array
var str [5]int = [5]int{1,2,3,4,5} for index,val := range str{ Statement block }
index is equivalent to subscript and val is equivalent to value
13. Use of multi-layer loop break and continue
lable1: for i:=1;i<10;i++{ lable2: for j:=1;j<10;j++{ } }
Break is to jump out of the loop and execute the statement after the loop, but break can only jump out of one layer of loop by default, so you need to add a label before the loop, and use break lable1 to indicate which loop to jump out of
Like break, continue can only jump out of one cycle. The difference is that continue jumps out of this cycle and continues to the next cycle
14.goto basic introduction (not recommended)
num1 :=1 if num1 == 1{ goto lable1 } fmt.println("Hello 1") lable1: fmt.println("Hello 2")
The output will be "Hello 2"
15. Basic syntax of function definition:
func Function name(Parameter type)(Return value (type){ Execute statement }
16. Some knowledge points of the package
The go search path is found from src under the GOPATH directory by default
The package of the package can be customized
If you need function or variable names to be used by other packages, the first letter must be capitalized
When using the pilot package: import custom name "path"
17. Packing syntax
go build -o specifies the package name to be typed in the path
If the specified path does not exist, create it yourself
18. Details of custom types
type mytype int
Although the custom type mytype is an int type, it is not completely consistent
There is no operation between them. Before operation, it needs to be converted to int type
19.func can be passed as a parameter
func mytype1(num1 int, num2 int)int{ } func mytype2(n1 func(int,int)int, num1 int, num2 int){ Statement block } fun main(){ num1 := 1 num2 := 2 mytype2(mytype1,num1,num2) }
20. Variable parameters
func args1(args... int){ fmt.Println(args) } func main(){ args1(1,2,3,4) }
args is a slice type of data
21.init function details
When an init function is defined in your package, init will be called before the main function
22. Anonymous function details
func (n1 int, n2 int)int{ return n1+n2 }(n1,n2) or a := func (n1 int, n2 int)int{}(n21,n2)
Anonymous functions are called directly after the function is created
23. Closure
func Addupper()func(int,int)int{ return func(n int,n2 int)int{ return n+n2 } } func main(){ add := Addupper() num3 := add(2,3) fmt.Println(num3) }
24.defer delay mechanism
Defer is used inside the function. When the function is executed, the statements after defer will be executed automatically. It is generally used to close the connection to the database
25. Time and date
import "time" now := time.Now() # Get current time now.Format("2006-0102 15:04:05") #Format date time now.Unix() #Seconds timestamp now.UnixNano() #Nanosecond timestamp
26. Catch exception defer+recover
defer func(){ err := recover() //revcover can catch exceptions if err != nil{ fmt.Println("err",err) } }
The biggest function of catching exceptions is that when the program reports an error, the following code can also be executed
27. Custom exception errors New and panic built-in functions
import "errors" errors.New("Code execution error") Panic(err)
The biggest function of the custom exception is that when the file is read incorrectly, the following code cannot be executed and the program needs to be terminated
28. Array (value type)
var num [3]int = [3]int{1,2,3} var num = [...]int{8,9,10} var num = [...]int{0:8,1:9,2:10}
29.slice slice (value type)
var num [3]int = [3]int{1,2,3} var slice1 := num[:] var slice2 := make([]int,4,10) #4 is the size and 10 is the capacity var slice3 []int = []int{1,2,3}
Note: there is a big difference between slice and array. The size of array is fixed and the slice size can be changed
var slice1 []int = []int{1,2,3} slice1 = append(slice,4) var slice2 = make([]int,1) copy(slice2,slice1) #copy the data of slice1 to slice2
30. Map (reference type) key value data structure
var a map[string]string := make(map[string]string) Addition and modification: a["key"] = value Delete: delete(a,"key") Check: val,finRes := a["key"]
If you traverse a map, you can only use for range traversal
31. Structure
type Logins struct { Username string `json:"userename"` Password string `json:"password"` }
Serialization / deserialization
import "encoding/json" var u Logins = Logins{"Username":"123","Password":"123"} Serialization: jsonstr,err := json.Marshal(Structure variable) if err != nil{ fmt.Println("Serialization error") } Deserialization: json.Unmarshal([]byte(jsonstr),&u)