Main content from the Chinese version of the official tutorial Go language Tour
Objective to summarize the main points
Pointer
Go has pointers. The pointer holds the memory address of the value.
*T
a type is a T
pointer to a type value. Its 0 value is nil
.
var p *int
&
operator generates a pointer to its operand.
i := 42p = &i
*
The operator represents the underlying value that the pointer points to.
fmt.Println(*p) // 通过指针 p 读取 i*p = 21 // 通过指针 p 设置 i
This is often referred to as an "indirect reference" or "redirect."
Unlike C, Go has no pointer operation.
package mainimport "fmt"func main() { i, j := 42, 2701 p := &i // point to i fmt.Println(*p) // read i through the pointer fmt.Println(p) *p = 21 // set i through the pointer fmt.Println(i) // see the new value of i p = &j // point to j *p = *p / 37 // divide j through the pointer fmt.Println(j) // see the new value of j}// output// 42// 0xc420084010// 21// 73
Structural body
A struct is a collection of variables that can be created in the following ways. Modifying structs can take .
symbols, and pointers to structs can be accessed in the same way.
package mainimport "fmt"type Vertex struct { X int Y int}func main() { v := Vertex{1,2} fmt.Println(v) v.X = 4 fmt.Println(v) p := &v p.X = 8 fmt.Println(v)}//output {1 2} {4 2} {8 2}
Pointers to structs and structs can be initialized in the following way
package mainimport "fmt"type Vertex struct { X, Y int}var ( v1 = Vertex{1, 2} // has type Vertex v2 = Vertex{X: 1} // Y:0 is implicit v3 = Vertex{} // X:0 and Y:0 p = &Vertex{1, 2} // has type *Vertex)func main() { fmt.Println(v1, p, v2, v3)}
Arrays and slices
The declaration of an array is also from the right, to var
the beginning or the short declaration
var a [2] stringvar a [10] intprimes := [6]{2, 3, 5, 7}
Slice
[]T
a type represents a slice of an element type T
. The slice is defined by two subscript a[low:high]
, which selects a half-open interval, contains the first element but excludes the last element. The default value for the lower bound of the slice is 0, and the default value for the upper bounds is the length of the slice. Note here that if the length is set, then the array is obtained, and in go the array is passed as a value, which consumes a lot of memory.
package mainimport "fmt"func main() { primes := [6]int{2, 3, 5, 7, 11, 13} // 这是一个数组 var s []int = primes[1:4] // 这是在声明一个切片 fmt.Println(s) names := [4]string{ "John","Paul","George","Ringo", } // 这是一个数组 fmt.Println(names) a := names[0:2] // 这也是一个切片 b := names[1:3] // 这也是一个切片 fmt.Println(a, b) // output [John Pul] [Paul George] b[0] = "XXX" fmt.Println(a, b) // output [John XXX] [XXX George] fmt.Println(names) // output [John XXX George Ringo]}
A slice itself is a reference to the underlying array, and multiple slices can share an underlying array, and modifications on one slice can affect the underlying array, which in turn affects all slices
Slices have length and capacity . For slices, the length is the length of the slice, which can be obtained s
len(s)
, and the capacity is obtained from the first element of the slice from the beginning of the number until the length of the underlying array cap(s)
.
From the perspective of the underlying array, there are only three meaningful slices in the slice, starting position, length, and capacity, respectively. Where the length and capacity are reflected in the slice itself, the starting position is used to anchor the slice in the underlying array position. Once a slice is created, the lower-level array is discarded before the starting position.
In doing the slicing, in fact, in the selection of the s[low: high]
low
current bottom array in the starting position, high
Select the end position, and then define the length high-low
. After the resume slices, the underlying array is condensed to the low
end of the original underlying array.
nil
Slices are slices whose length and capacity are zero, and do not have a slice of the underlying array, such as it can declare var s []int
. In this sense, the array itself is a slice of equal length and capacity.
Slices can contain any type, or even other slices (multidimensional arrays)
board := [][]string{ []string{"_", "_", "_"}, []string{"_", "_", "_"}, []string{"_", "_", "_"},}
Use
range
Traversing slices
package mainimport "fmt"var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}func main() { for i, v := range pow { fmt.Printf("2**%d = %d\n", i, v) } for _, value := range pow { fmt.Printf("%d\n", value) } for value, _ := range pow { fmt.Printf("%d\n", value) }}
Mapping
The map maps the key to value. make
You can use a function to create a map of a given type and initialize it as an alternative.
The 0 value of the mapping nil
is that there is nil
neither a key nor a key to add
package mainimport "fmt"type Vertex struct { Lat, Long float64}var m map[string]Vertexfunc main() { m = make(map[string]Vertex) m["Bell Labs"] = Vertex{ 40.68433, -74.39967, } fmt.Println(m["Bell Labs"])}
Mapped grammars and structs are similar, but must have key names
package mainimport "fmt"type Vertex struct { Lat, Long float64}var m = map[string]Vertex{ "Bell Labs": Vertex{ 40.68433, -74.39967, }, "Google": Vertex{ 37.42202, -122.08408, },}func main() { fmt.Println(m)}
Mappings can use subscripts to access or modify elements
Delete an element with a delete
function
Use double assignment to detect the presence of a key
package mainimport "fmt"func main() { m := make(map[string]int) m["Answer"] = 42 fmt.Println("The value:", m["Answer"]) m["Answer"] = 48 fmt.Println("The value:", m["Answer"]) delete(m, "Answer") fmt.Println("The value:", m["Answer"]) v, ok := m["Answer"] fmt.Println("The value:", v, "Present?", ok) // ok 是是否存在的boolean值}
function value
The function itself can also be used as a value, called a function value, as a function parameter or as a return value
package mainimport ( "fmt" "math")func compute(fn func(float64, float64) float64) float64 { return fn(3, 4)}func main() { hypot := func(x, y float64) float64 { return math.Sqrt(x*x + y*y) } fmt.Println(hypot(5, 12)) fmt.Println(compute(hypot)) fmt.Println(compute(math.Pow))}
The Go function can make a closure. A closure is a function value that refers to a variable within a function body. The function can access and give the value of the variable it references. For example, the function return value in the following example adder
is a closure. Each closure is bound to its own sum
variable.
package mainimport "fmt"func adder() func(int) int { sum := 0 //这是闭包的函数体之外的变量,它也被绑定在闭包内了 return func(x int) int { //这是闭包 sum += x return sum }}func main() { pos, neg := adder(), adder() for i := 0; i < 10; i++ { fmt.Println( pos(i), neg(-2*i), ) }}
Make function
Use the Make function to create slices (dynamic arrays), there are two ways to use
a := make([]int, 5) // 长度为5,容量默认为5b := make([]int, 0, 5) // 长度为0, 容量为5
func make([]T, len, cap) []T
make
a function allows you to create a map of a given type and initialize it with an alternate
Go get started-the complex type in Go