Go language core programming (7)-language trap

Go language core programming (7)-language trap

Note: This article is a personal reading note of "Go Language Core Programming" (Li Wenta/Work)

Multi-finger assignment

Rule 1 Variables of the same type can have a type at the end. 2 If there is no type, then type inference is performed. 3 Multi-value assignment statements cannot be followed by a type format. The right side of each variable can be a return function expression, which can be range to map clice, etc. The operation of the function can also be that the left side of the type inference assignment needs to have the same number of values ​​as the right side, and the values ​​are assigned sequentially from left to right

range reuse temporary variables

The value of the iteration variable under for range is shared

defer

Side effects defer may modify the return value. Defer's impact on performance is to use the format without the return value name in the definition of the function. In this way, defer cannot directly refer to the stack area of ​​the return value, which prevents the return value from being modified. The problem

Array

An array is a data structure with the same element type fixed, and the bottom layer is stored in a continuous memory address space. Once the array size is declared, it cannot be changed. Array creation method 1 Specify size display initialization 2 Pass... Infer the size of the array from the following element format 3 Specify the size and initialize it by the index value, the element that is not displayed initialized is set to the type zero value 4 Specify the size but do not display Initialization, the array element is set to zero. All transfers of the array are value copies 1 Direct assignment between arrays 2 Arrays as function parameters 3 Arrays are embedded in struct

slice

Create sections 1 through 3 to create an array of directly creating 2 make a statement through the slice data structure the data structure has three members, namely, the pointer pointing to the bottom of the array, and the size of the current size of the underlying array of slices. when! When en grows more than cap, it will apply for a larger-capacity bottom array, and copy the data from the old array to the newly applied array.

//src/runtime/slice. go
type slice struct {
array unsafe .Pointer
len int
cap int
}
Reference: https://cloud.tencent.com/developer/article/1438476 Go language core programming (7)-language trap-cloud + community-Tencent Cloud