1. Basic knowledge

1. Basic data types

  • Value type:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
bool (length 1Byte or 1 byte)
byte (1 byte, uint8 alias)
rune (4 bytes, int32 alias, -231~231)
int (32 or 64, length 4 or 8 bytes)
int8 (length 1 byte), int16 (length 2 bytes), int32 (length 4 bytes), int64 (length 8 bytes)
uint (32 or 64, length 4 or 8 bytes)
uint8 (length 1 byte), uint16 (length 4 bytes), uint32 (length 4 bytes), uint64 (length 8 bytes)
float32 (length 4 bytes), float64 (length 8 bytes)
string //A sequence of fixed-length characters connected together, the underlying layer is a byte array
complex64, complex128 (default) //Complex type
array //Array (fixed length)
struct //Structure
  • Reference type (pointer type):
1
2
3
slice //Sequence array, default value nil
map //Map, default value nil
chan //Pipe, default value nil

2. Encoding && string

The default encoding of golang is UTF-8

  • Unicode: A global character encoding standard, variable length encoding, with multiple implementation methods, its purpose is to unify all text encodings, such as UTF-8, UTF-16, etc., the length range is 1-4 bytes, the default English occupies 1 Byte, Chinese occupies 2 Byte; each character corresponds to a hexadecimal number, the Unicode string length is obtained using the utf8.RuneCountInString() function.
  • UTF-8: It is a variable length character encoding, and it is also one of the Unicode implementation methods. English occupies 1 Byte, Chinese occupies 3 Byte, and emoji occupies 4 Byte.

There are two types of characters in GO, one is byte and the other is rune

  • byte: It is an alias for uint8, often used to process ASCII characters, representing a string of ASCII codes, []byte(s), converts s to a byte array.
  • rune: is an alias of int32, equivalent to the int32 type, usually used to represent the code point of a unicode character, can handle all characters, the usage method is []rune(s), convert s to a unicode array

string: a sequence of fixed-length characters connected, the underlying byte array, the string is immutable, when the string only has numbers and letters, it can be converted to []byte or []rune, when there are multi-byte encodings such as Chinese characters, it must be converted to []rune, the most common method is to convert to []rune(s)

  • Single quotes: used to represent byte type or rune type, the default is rune type, the content in single quotes is Ascii code characters, and the ASCII string length is obtained using the len() function;

  • Double quotes: indicates that string literals can be parsed, supports escape, but cannot be used to quote multiple lines;

  • Backquotes: used to create native string literals, does not support any escape sequences, supports multiple lines, and is mostly used to write multi-line messages, html, and regular expressions;

3. Built-in functions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
append // Used to append elements to arrays and slices, and return the modified arrays and slices
close // Mainly used to close channels
delete // Delete the value corresponding to the key from the map
panic // Stop the regular goroutine (panic or recover: used for error handling)
recover // Allow the program to define the panic action of goroutine
real // Return the real part of complex (complex, real, imag are used to create and operate complex numbers)
imag // Return the imaginary part of complex
make // Used to allocate memory and return the Type itself (can only be used for slice, map, channel)
new // Used to allocate memory, mainly used to allocate value types, such as int, struct, and return a pointer to type.
cap // used to return the maximum capacity of a type, can only be used for slices and maps
copy // used to copy and connect slices, return the number of copies
len // get the length, such as string, array, slice, map, channel
print, println // underlying printing function

2. Common placeholders:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Placeholder Description Example Output
%v The default format of the corresponding value. Printf("%v", people) {zhangsan},
%+v When printing a structure, the field name will be added Printf("%+v", people) {Name:zhangsan}
%#v Go syntax representation of the corresponding value Printf("#v", people) main.Human{Name:"zhangsan"}
%T Go syntax representation of the type of the corresponding value Printf("%T", people) main.Human
%% Literal percent sign, not a placeholder for the value Printf("%%") %
%t Boolean placeholder true or false. Printf("%t", true) true
%c character placeholder, the character represented by the corresponding Unicode code point Printf("%c", 0x4E2D)
%d integer placeholder, decimal representation Printf("%d", 0x12) 18
%s string placeholder (string type or []byte) Printf("%s", []byte("Go language")) Go language
%p pointer placeholder, hexadecimal representation, prefix 0x Printf("%p", &people) 0x4f57f0

3. Array && slice && map

1. Array

var array variable name [number of elements] type The length of the array must be a constant. Once defined, the length cannot be changed, but the elements in the array can be changed

1
var a[5]int

Declare an array of length 5 and type int

1
2
3
4
5
6
a := [8] int{0, 1, 2, 3, 4, 5, 6, 7}
b := a[3:6]
// 8 8
fmt.Println(len(a), cap(a))
// Value: [3 4 5], length: 3, capacity: 5
fmt.Printf("Value: %d, length: %d, capacity: %d", b, len(b), cap(b))

2. Slice

A variable sequence with elements of the same type. It is a layer of encapsulation based on arrays. It is very flexible and supports automatic expansion. Slice is a reference type, which contains address, length (len), and capacity (cap)

Syntax: var slice variable name [] type

1
2
3
4
5
6
7
8
var a [] string //Declare a length of 0 and type string slice.
var a[]string{} //Declare a length of 0, type string, and initialize

var myslice = []string{"Beijing", "Shanghai", "Shenzhen"}

for i := 0; i < len(myslice); i++ {
fmt.Println("for loop:", myslice[i])
}

3. map

An unordered, key/value-based data structure. In go, map is a reference type and must be initialized with make before it can be used.

Syntax: map[keytype]valuetype

The default initial value of map is nil. The make() function needs to be used to allocate memory. Cap represents the capacity of the map. Although this parameter is not required, cap cannot be used to obtain the capacity of the map. Cap returns the size of the space allocated by the array slice; to obtain the capacity of the map, the len function can be used.

1
2
3
4
5
6
7
userInfo := map[string]string{
"username": "xiaoli",
"password": "1234556",
}
for k, v := range userInfo {
fmt.Println(k, v, len(userInfo))
}

4. Pointer:

In Go language, reference data types must not only be declared, but also allocated memory for them, otherwise our values ​​will not be stored; and for value type declarations, there is no need to allocate memory, because they have already allocated memory by default.

1
2
3
4
Pointer address: &a
Pointer value: *&a
Pointer type: &a --> *int
& value, * follow address value

new: Apply for a piece of memory space for the type and return a pointer. For example, for structure instantiation, the pointer address of the structure is returned

make: Only used for memory creation of chan, map, and slice, and its return type is the three types themselves, not their pointer types.

5. Structure

There is no concept of class in the Go language, nor does it support object-oriented concepts such as class inheritance; the Go language mainly uses structure embedding and interfaces to achieve higher scalability and flexibility than object-oriented programming.

1. Structure instantiation method:

Direct assignment (var), new, key-value pair instantiation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import "fmt"

// Define a structure
type member struct {
name string
city string
age int
}

func main() {
var p1 member //Direct assignment instantiation structure
p1.name = "Xiao Ming"
p1.city = "beijing"
p1.age = 32

var p2 = new(member) //New keyword instantiation
p2.name = "Xiao Li"
p2.city = "shanghai"
p2.age = 20

p3 := &member{
name: "Xiao Zhang",
city: "shenzhen",
age: 18,
} // Key-value pair instantiation
fmt.Printf("p1=%v \n", p1) // Output value
fmt.Printf("p1=%+v \n", p1) // Output the structure and add the field name
fmt.Printf("p2=%#v \n", p2) // Output the structure field and return the syntax representation
fmt.Printf("p3=%#v \n", p3)
}

Output result:

1
2
3
4
p1={Xiaoming beijing 32}
p1={name:Xiaoming city:beijing age:32}
p2=&main.member{name:"Xiao Li", city:"shanghai", age:20}
p3=&main.member{name:"Xiao Zhang", city:"shenzhen", age:18}

2. Struct methods and receivers

The method of the Go language is a function of a specific type of variable. This specific type is called a receiver. The concept of a receiver is similar to this, self, etc. in other languages.

Syntax:

1
2
func (receiver variable, receiver type) method name (parameter list) (return value) {
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import "fmt"

// Define a structure
type Person struct {
name string
age int
city string
}

// Value receiver
func (p Person) printInfo() {
fmt.Printf("Name: %s, Age: %d, City: %s \n", p.name, p.age, p.city)
}

// Pointer receiver
func (p *Person) setInfo(name string, age int, city string) {
p.name = name
p.age = age
p.city = city
}

func main() {
// Instantiate structure
p1 := Person{
name: "xiaoming",
age: 15,
city: "tianjin",
}
p1.printInfo() //Name: xiaoming, age: 15, city: tianjin
p1.setInfo("tiantian", 18, "beijing")
p1.printInfo() //Name: tiantian, age: 18, city: beijing
}