Hello everyone, today I will comb out the basic grammar content of Go language and share it with you. Thanks for your advice.
This “Go Language Basic Grammar Content” is divided into three chapters, this paper is the first chapter
- Golang Foundation (1)
- Golang Foundation (2)
- Golang Foundation (3)
Contents of this chapter
- Go keyword
- The sample Demo
- Declaration, assignment
- Reference types
- slice
- map
Go keyword
Go language has a total of 25 keywords, the basic syntax section will introduce the use of all keywords.
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
Copy the code
List of predefined names
// Built-in constants
true false iota nil
// Built-in type
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
float32 float64 complex128 complex64
bool byte rune string error
// Built-in function
make len cap new append copy close delete
complex real imag
panic recover
Copy the code
The built-in functions section will be covered in subsequent sections.
The sample Demo
The above Go language sample code is mainly composed of three parts:
The first part imports the package name, the default is main;
The second part import standard library;
In the go language, if the code needs to run, it must have a main function as an entry point.
Traditionally, Go programmers recommend camelback naming, with case separation preferred to underscore separation when names consist of several words.
package
Package refers to the package that belongs to. In go, the directory structure is called package. If there is a main() function in the code, the current package must be main.
package main
Copy the code
import
Import standard or third-party libraries
import "fmt" // Single is supported
import ( // Support multiple
"log"
alias "other/xxxx" // Support library alias Settings
_ "other/xxxs" // Support libraries load libraries by default
)
Copy the code
Declaration, assignment
Go has four main types of declarations: var, const, type, and func, which correspond to declarations of variables, constants, types, and function entity objects, respectively.
When using multiple assignments, if you want to ignore a value, you can use anonymous variables that are represented by an underscore _.
Anonymous variables take up no namespace and no memory is allocated, so there are no duplicate declarations between anonymous variables.
var
The var declaration statement creates a variable of a particular type, appends it to a name, and sets its initial value.
General syntax for variable declarations:
// var Variable name type = expression
var name string = "The Gunslinger of Hat Hill."
Copy the code
Numeric variables have a zero value of 0, Boolean variables have a zero value of false, string variables have a zero value of empty string, and interface or reference variables (including slice, pointer, map, chan, and function) have a zero value of nil
You can also declare a set of variables together in a declaration statement, or declare and initialize a set of variables with a set of initialization expressions.
var i, j, k int // int, int, int
var b, f, s = true.2.3."four" // bool, float64, string
Copy the code
A set of variables can also be initialized by calling a function with multiple return values returned by the function
var f, err = os.Open(name) // os.Open returns a file and an error
Copy the code
Variable declarations in Go must be separated by Spaces
var age int
Copy the code
Define string array syntax
var strArrar1 []string // The declaration type is string array
var strArrar2 []string{"a"."b"} // Initialize the value
Copy the code
const
The value of a constant expression is evaluated at compile time, not run time. The underlying type of each constant is the base type: Boolean, String, or number. The value of a constant cannot be modified, which protects it from accidental or malicious modification at run time.
/ / declare
const num = 10
Copy the code
type
A newly named type is used to separate types of different concepts so that they are not compatible even if the underlying type is the same
// type Indicates the underlying type of the type name
type Num float64
Copy the code
Type declaration statements generally occur at the package level, so if the first character of a newly created type name is uppercase, it can be used outside the package.
func
A function declaration includes the function name, formal parameter list, return value list (optionally omitted), and function body.
func name(param) (result) {
// body
}
Copy the code
Function takes parameters and returns a value of type float64
func hypot(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
Copy the code
Defer usage
Defer is called late and is usually used to execute last in a function
func example(a) {
defer func(a) {
fmt.Println("Last execution")
}
fmt.Println("Execute first")}Copy the code
Reference types
- slice
- map
- channel
slice
introduce
Slice represents a variable-length sequence in which each element has the same type. A slice type is written as []T, where T stands for the type of the slice element; Slice’s syntax is similar to that of an array, except that there is no fixed length.
Arrays and Slice are closely related. A slice is a lightweight data structure that provides access to subsequence (or all) elements of an array, and the underlying slice does reference an array object. A slice consists of three parts: pointer, length, and volume. Pointers to the address of the underlying array element corresponding to the first slice element. Note that the first slice element is not necessarily the first element in the array. Length corresponds to the number of elements in slice; The length cannot exceed the capacity, which is typically from the start of slice to the end of the underlying data. The built-in len and CAP functions return the length and size of slice, respectively.
Underlying data can be shared between multiple slices, and portions of the array referenced may overlap.
The slice value contains a pointer to the first slice element, so passing slice to a function allows the elements of the underlying array to be modified inside the function. In other words, copying a slice simply creates a new Slice alias for the underlying array.
Unlike arrays, slices cannot be compared, so we cannot use the == operator to determine whether two slices contain all equal elements.
A zero-valued slice equals nil. A nil slice has no underlying array. A nil slice has a length and capacity of 0, but there are non-nil slices that have a length and capacity of 0, such as []int{} or make([]int, 3)[3:]. As with any nil value, we can use a []int(nil) conversion expression to generate a nil value of the corresponding type slice.
use
Use the built-in make function to create a slice that specifies the element type, length, and capacity. The capacity part can be omitted, in which case the capacity will be equal to the length.
make([]T, len) // omit the capacity
make([]T, len.cap) / / capacity
Copy the code
You can append multiple elements and even a slice using the built-in Append function
var x []int
x = append(x, 1)
x = append(x, 2.3)
x = append(x, 4.5.6)
Copy the code
map
introduce
A hash table is an ingenious and useful data structure. It is an unordered collection of key/value key-value pairs, where all keys are different, and corresponding values can then be retrieved, updated, or deleted in constant time complexity with a given key.
In Go, a map is a reference to a hash table. The map type can be written as map[K]V, where K and V correspond to key and value respectively. All keys in a map have the same type, and all values have the same type. However, keys and values can be of different data types. The key corresponding to K must be a data type that supports the == comparison operator. Therefore, map can test whether the key is equal to determine whether it already exists.
The zero value of the map type is nil, that is, no hash table is referenced.
use
Create a map using the built-in make function
ages := make(map[string]int)
Copy the code
You can create a map using the syntax of a map literal and assign a key/value
ages := map[string]int{"age1": 18."age2": 19}
Copy the code
The other creates an empty Map expression
ages := map[string]int{}
Copy the code
Elements in a Map are accessed by key subscript syntax
ages["age1"] = 18
fmt.Println(ages["age1"])
Copy the code
Elements can be deleted using the built-in delete function
delete(ages, "age1") // It does not matter if some elements are not in the map, 0 is returned on failure.
Copy the code
To iterate over all key/value pairs in a map, use a range-style for loop
for name, age := range ages {
fmt.Printf("%s\t%d\n", name, age)
}
Copy the code
Address fetching of map elements is prohibited because the map may reallocate more memory space as the number of elements increases, which may invalidate the previous address.
Technical articles continue to be updated, please pay more attention to it