Array Array and slice Slice

Array Array
- need to specify capacity and initial value when declaring, fixed length, access by index.
Initialization:
Demo:
var arr [5]int //declare an array with a size of 5, the default initialization value is [0,0,0,0,0]
arr := [5]int{1} //declare and The first element of an array with a size of 5 is initialized, and the value after initialization is [1,0,0,0,0]
arr := […]int{1,2,3} //Get the array automatically through ... Length, the size is initialized to 3 according to the number of initialized values, and the value after initialization is [1,2,3]
arr := […]int{4:1} //The value of the element whose serial number is 4 is 1, The length is automatically obtained by ..., and the value after initialization is [0,0,0,0,1]
Function parameters
- pass by value, specify the size

Slice
- dynamic length array, index/slice access
- pointer (slice), length, capacity (insufficient capacity, capacity * 2)
initialization:
s := []int{1,2,3} // through the reference of the array Initialization, the value is [1,2,3], the length and capacity are 3
arr := [5]int{1,2,3,4,5}
s := arr[0:3] // slice through the array Initialization, the value is [1,2,3], the length is 3, and the capacity is 5
s := make([]int, 3) //Initialize through the make function, the value is [0,0,0], the length and capacity is 3
s := make([]int, 3, 5) //Initialized by the make function, the value is [0,0,0], the length is 3, and the capacity is 5 (the value of
x is [2,3,5 ,7,11], the value of y is [3,5,7], and the pointers of the two slices point to the same array,
- when the slice operation is initialized, use append to copy the data to a new slice, So as to avoid x large array memory occupation)
function parameters
- passed by reference,
(since the passed function is a copy of the pointer, so the modification of the pointer will not cause the change of the original pointer, for example, the append function will not change the original slice value)
Demo
func PrintSlice(s []int) { s = append(s, 4) s[0] = -1 fmt.Println(s) } s := []int{1,2,3,4 ,5}





s1 := s[0:3]
fmt.Println(“s:”,s) //s: [1,2,3,4,5]
fmt.Println(“s1:”,s1) //s1: [1,2,3]
PrintSlice(s1) //[-1,2,3,4]
fmt.Println(“s:”,s) //[-1,2,3,4,5]
fmt.Println(“s1:”,s1) //[-1,2,3]

Guess you like

Origin blog.csdn.net/qq_34751210/article/details/127763551