1. Go’s Data Structures
Basic types
- Boolean: bool
- Integer: byte, int, int8, int16, uint, uintptr
- Floating point: float32, float64
- Complex: complex64, complex128
- String: string
- Character: rune
- Error: error
Composite types
- Pointer: pointer
- Array: array
- Slice: slice
- Dictionary: map
- Channel: chan
- Struct: struct
- Interface: interface
A Go variable identifier is made up of letters, digits, and underscores, and its first character cannot be a digit. When declaring a variable, the type goes after the variable identifier. The general form is:
| |
When declaring a variable, if it is not initialized it defaults to the zero value. For a variable declaration with an initial value, the type can be omitted, because Go can infer the type.
| |
2. Go’s Logic Structures
- Loop structure for
| |
| |
- Conditional branches if, switch
| |
| |
- Jump goto
goto can jump unconditionally to a specified label
| |
- Defer defer
A defer statement is pushed onto a stack, and when the outer function returns, the statements are popped off and executed in order.
| |
3. Go’s Module Definitions
3.1 Functions
The format for defining a Go function:
| |
- func, the function declaration keyword
- function_name, the function name, which together with the parameter list forms the function signature
- parameter list, the parameter list
- return_types, the return type
An example:
| |
A Go function can also return multiple values:
| |
In addition, Go also lets you declare an anonymous function and assign it directly to a variable:
| |
3.2 Packages
Go uses package to manage code, similar to Python. A package is a collection of one or more Go source files. Go has many built-in packages, such as fmt, os, io, and so on.
To declare a package, add the following identifier on the first line of the file:
| |
To import it, add the following identifier at the top of the file:
| |
Features of package:
- Sibling files in the same directory belong to one package
- The package name and the directory name can differ, but they are usually kept consistent
- A program’s entry point is the main function of the main package; if there is no main package, no executable file is generated
- Only identifiers whose first letter is uppercase are accessible outside the package
