An overview of the
The three consecutive sections are as follows:
- The first section covers basic syntax and data structures
- Section 2 discusses methods and interfaces
- The third section briefly introduces the concurrency primitives of Go.
The import package import
If a name begins with a capital letter, it is exported. For example, Pizza is an exported name, as is Pi, which is exported from the Math package.
Import grouping import "FMT" import "math"Copy the code
However, it is better to use grouped import statements.
import (
"fmt"
"math"
)
Copy the code
Function parameter abbreviation
Func add(x int, y int) int {return x + y} (x, y int) int {return x + y}Copy the code
Meaningful return values The return values of Go can be named, and they are treated as variables defined at the top of the function.
Var statement is used to declare a variable var C, Python, Java bool
Short variable declarations In functions, the succinct assignment statement := replaces the var declaration where the type is explicit. The := structure cannot be used outside functions.
The basic types of Go are
Bool STRING int INT8 INT16 INT32 INT64 UINT UINT8 UINT16 uint32 Uint64 UintpTR Byte // Alias of uint8 RUNe // alias of INT32 // A Unicode code point float32 float64 complex64 complex128Copy the code
Type conversion
The expression T(v) converts the value v to type T.
i := 42
f := float64(i)
u := uint(f)
var i int = 42
var f float64 = float64(i)
Copy the code
Type derivation When declaring a variable without specifying its type (that is, using the untyped := syntax or var = expression syntax), the type of the variable is derived from an rvalue.
constant
Constants are declared like variables, but with the const keyword. For is “while” as in Go.
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
}
Copy the code
defer
The defer statement will defer execution of the function until the outer function returns.
A delayed function is evaluated immediately, but is not called until the outer function returns. Delayed function calls are pushed onto a stack. When the outer function returns, the delayed function is called in last-in, first-out order.
Go has Pointers. Pointers hold the memory address of the value.
Type *T is a pointer to a value of type T. Its zero value is nil.
The var p *int & operator generates a pointer to its operand.
i := 42
p = &i
The structure of the body
A struct is a group of fields
An array of
The length of an array is part of its type, so arrays cannot be resized var a [10]int
slice
Type []T represents a slice whose element type is T. A slice is defined by two subscripts, an upper bound and a lower bound, separated by a colon: A [low: high] a[1:4] It contains elements of A with subscripts from 1 to 3:
A slice is like a reference to an array a slice doesn’t store any data, it just describes a segment of the underlying array. Changing an element of a slice modifies the corresponding element in its underlying array. Slicing grammar is similar to array grammar without length. This is an array grammar: [3]bool{true, true, false} The default lower bound of the slice is 0, and the upper bound is the length of the slice. The following slices are equivalent:
a[0:10]
a[:10]
a[0:]
a[:]
Copy the code
Length and capacity of a slice A slice has both length and capacity. The length of a slice is the number of elements it contains. The size of a slice is the number from its first element to the end of its underlying array element. The length and capacity of slice S can be obtained by the expressions len(s) and Cap (s). Nil slice zero is nil, the way you create slices with make, create dynamic arrays. The make function allocates an array with zero elements and returns a slice that references it:
a := make([]int, 5) // len(a)=5
Copy the code
Slices of slices are two-dimensional arrays
board := [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}
Copy the code
Range
The range form of the for loop traverses slices or maps. When a slice is iterated over using the for loop, two values are returned for each iteration. The first value is the subscript of the current element, and the second value is a copy of the element to which the subscript corresponds.
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
Copy the code
It can be ignored by assigning a subscript or value to _.
for i, _ := range pow
for _, value := range pow
Copy the code
If you only need the index, ignore the second variable.
for i := range pow
Copy the code
Map
It's just a data structure that implements a map of key-value pairs that maps keys to values. The zero value of the map is nil. Nil maps have no keys and can't add keys. Var m map[string]Vertex m = make(map[string]Vertex) m["Bell Labs"] = XXXXXXXCopy the code
Grammar of a map The grammar of a map is similar to that of a structure, but must have a key name.
Var m = map[string]Vertex{"Bell Labs": Vertex{40.68433, -74.39967,}, Vertex{37.42202, -122.08408,},} If the top-level type is only a type name, you may omit it from the elements of the grammar. Var m = map[string]Vertex{"Bell Labs": {40.68433, -74.39967}, "Google": {37.42202, -122.08408},}Copy the code
To insert or modify elements in mapping M:
m[key] = elem
Copy the code
Get elements:
elem = m[key]
Copy the code
Delete element:
delete(m, key)
Copy the code
Check the existence of a key by double assignment:
elem, ok = m[key]
Copy the code
If key is in m, ok is true; Otherwise, ok is false. If key is not in the map, elem is the zero value of the mapping element type.
Function value
Functions are also values. They can be passed like any other value. A function value can be used as a parameter or return value of a function. PS: Functions can be passed as arguments
Closure of a function The Go function can be a closure. A closure is a function value that references variables outside of its function body. The function can access and assign values to the variables it references; in other words, the function is “bound” by those variables.
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
Copy the code
A named return parameter can return multiple results as Python does, but not a tuple. An unwanted return value can be thrown in the trash. If a named parameter is returned, the return statement can be null. Return is not null and returns values in the order in which they were returned, not in the order declared in the function header
package main func change(a, b int) (x, y int) { x = a + 100 y = b + 100 return //101, 102 //return x, //return y, x //102, # 101} more learning materials [http://docscn.studygolang.com/doc/] (http://docscn.studygolang.com/doc/) https://go-zh.org/# https://tour.go-zh.org/list ENDCopy the code