Go language basics
Table of contents
built-in type
Value type:
bool
int(32 or 64), int8, int16, int32, int64
uint(32 or 64), uint8(byte), uint16, uint32, uint64
float32, float64
string
complex64, complex128
array -- 固定长度的数组
Reference type: (pointer type)
slice -- 序列数组(最常用)
map -- 映射
chan -- 管道
built-in function
- make(): used to create a new slice, map or channel. The parameters of the make() function include the type, length, and capacity to be created.
// 创建一个长度为5,容量为10的slice s := make([]int, 5, 10) fmt.Println(len(s)) // 5 fmt.Println(cap(s)) // 10 // 创建一个长度为5,容量为5的map m := make(map[string]int, 5) m["one"] = 1 fmt.Println(m) // map[one:1] // 创建一个容量为10的channel c := make(chan int, 10) c <- 1 fmt.Println(<-c) // 1
- append(): Used to add elements to the slice. If the capacity of the slice is insufficient, the append() function will automatically expand the capacity.
// 向slice中添加元素 s := []int{ 1, 2, 3} s = append(s, 4, 5, 6) fmt.Println(s) // [1 2 3 4 5 6]
- len(): Used to get the length of slice, map, string, array and channel.
s := []int{ 1, 2, 3, 4, 5} fmt.Println(len(s)) // 5 m := map[string]int{ "one": 1, "two": 2, "three": 3} fmt.Println(len(m)) // 3 str := "hello" fmt.Println(len(str)) // 5 arr := [5]int{ 1, 2, 3, 4, 5} fmt.Println(len(arr)) // 5 c := make(chan int, 10) c <- 1 fmt.Println(len(c)) // 1
- cap(): used to obtain the capacity of slice, array and channel.
s := []int{ 1, 2, 3, 4, 5} fmt.Println(cap(s)) // 5 arr := [5]int{ 1, 2, 3, 4, 5} fmt.Println(cap(arr)) // 5 c := make(chan int, 10) fmt.Println(cap(c)) // 10
- copy(): Used to copy the elements in a slice to another slice.
s1 := []int{ 1, 2, 3, 4, 5} s2 := make([]int, len(s1)) copy(s2, s1) fmt.Println(s2) // [1 2 3 4 5]
- close(): used to close a channel.
c := make(chan int, 10) c <- 1 close(c) fmt.Println(<-c) // 1 _, ok := <-c fmt.Println(ok) // false
- delete(): Used to delete elements in the map.
m := map[string]int{ "one": 1, "two": 2, "three": 3} delete(m, "two") fmt.Println(m) // map[one:1 three:3]
- panic() and recover(): used to handle exceptions in the Go language.
This is because the functionfunc test() { defer func() { if err := recover(); err != nil { fmt.Println("panic:", err) } }() panic("test panic") } func main() { test() fmt.Println("after test") } // 输出:panic: test panic
test()
is called in the functionpanic()
, causing an exception to occur in the program, and thendefer
the exception is caught and processed through the anonymous function in the statement. Specifically,defer
the statement will push an anonymous function into the function call stack, and wait for the current function to be executed before executing the anonymous function. In this example, a function is used in the anonymous functionrecover()
to catch the exception and output the exception information to the console. Sincerecover()
the function can onlydefer
take effect in the statement, it needs to be placeddefer
in the statement. Finally,main()
the function continues executing and outputsafter test
. - print() and println(): used to output content to the terminal.
name := "Alice" age := 20 fmt.Print("My name is ", name, ", and I'm ", age, " years old.") // 输出:My name is Alice, and I'm 20 years old. fmt.Println("My name is ", name, ", and I'm ", age, " years old.") // 输出: // My name is Alice, and I'm 20 years old. // (自动换行)
built-in interface error
type error interface {
//只要实现了Error()函数,返回值为String的都实现了err接口
Error() String
}
As you can see, error
the interface contains only one Error()
method, which returns an error message of type string. Therefore, if we want to customize an error type, we only need to implement Error()
the method.
Here is an example of a custom error type that represents a division by zero error:
type DivideError struct {
dividend int
divisor int
}
func (de *DivideError) Error() string {
return fmt.Sprintf("error: divide %d by %d", de.dividend, de.divisor)
}
func divide(dividend, divisor int) (int, error) {
if divisor == 0 {
return 0, &DivideError{
dividend, divisor}
}
return dividend / divisor, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}
In this example, we define a DivideError
structure that contains two variables, the dividend and the divisor. Then, we define a Error()
method for this structure that returns an error message when the divisor is zero. Next, we define a divide()
function that calculates the quotient of two numbers and returns the calculation result and an error message. DivideError
Returns an error of type if the divisor is zero . Finally, main()
call divide()
the function in the function, if the returned error is not empty, output the error message; otherwise, output the calculation result.
In short, error
interface is a very commonly used interface in Go language, which is used to express error information. In actual development, we often use error
interfaces to define error types and return error information to the caller. By using interfaces reasonably error
, we can improve the fault tolerance and robustness of the program.