Golang slice uses Daquan (create, initialize, traverse, intercept, modify, add, copy of slice, slice as function parameter, slice sum, slice maximum)

Posted by waynem801 on Thu, 27 Jan 2022 12:48:21 +0100

Concept:

The length of the slice is not fixed and data can be added. It is similar to the concept of dynamic array in Java. The reason for the emergence of the slice is also that the operability of the array is not high.

Dynamic initialization of array:

Array dynamic initialization is to give only the length of the array and the default initialization value is given by the system

Dynamic initialization & static initialization:

Dynamic initialization is used when the specific value is not known
Static initialization is used when the specific value is known

Slice creation:

Normal format:

var Slice name [] data type

Automatically derive types and create slices:

Slice name := [] type{}

Create slice with make function:
Length refers to the initialized space, and capacity refers to the opened space, including the initialized space and free space

// The length cannot be greater than the capacity. The capacity can be omitted. When it is not written, it defaults to the same value as the length
 Slice name := make ([]Slice type,Length capacity)

// cap is used to return the capacity of the slice, and len is used to return the length of the slice
fmt.Println(cap(Slice name))

demonstration:

func SliceDemo01() {
	//var slice [] int
	//slice := [] int{}
	slice := make([]int, 3, 4)

	fmt.Println("Data in slice", slice)
	fmt.Println("Slice length:", len(slice))
	fmt.Println("Slice capacity:", cap(slice))
}

Slice initialization:

The three creation formats can add data to the slice through append

Initialization format:

///Slices created in normal format
 Slice name [Indexes] = value 

// Automatically deduce slices created by type
 Slice name := [] type{Data 1,Data 2,Data 3}

// Slices created by the make function can be initialized by append and loop
 Slice name = append(Slice name, Data 1,Data 2...)

demonstration:

func SliceDemo2() {
	var slice []int
	slice = append(slice, 1, 2, 3, 4)
	slice[1] = 111
	fmt.Println("Data in slice", slice)
	fmt.Println("Partial data can be retrieved by index", slice[0])
	fmt.Println("Slice length:", len(slice))
}

func SliceDemo03() {
	slice := []int{1, 2, 3, 4, 5}
	slice = append(slice, 6, 7, 8, 9, 10)
	slice[1] = 111
	fmt.Println("Data in slice", slice)
	fmt.Println("Partial data can be retrieved by index", slice[0])
	fmt.Println("Slice length:", len(slice))
}

func SliceDemo04() {
	slice := make([]int, 3, 4)
	for i := 0; i < len(slice); i++ {
		slice[i] = i + 1
	}
	
	slice = append(slice, 1)
	fmt.Println("Data in slice", slice)
	fmt.Println("Partial data can be retrieved by index", slice[0])
	fmt.Println("Slice length:", len(slice))
	fmt.Println("Slice capacity:", cap(slice))
}

Slice traversal:

Traversal is the same as array, which can be obtained by ordinary for loop and range traversal

demonstration:

func SliceDemo05() {
	slice := []int{1, 2, 3, 4, 5}
	for i := 0; i < len(slice); i++ {
		fmt.Print(slice[i])
	}
	
	for _, v := range slice {
		fmt.Println(v)
	}
}

Slice interception:

Slice interception is to obtain the specified data from the slice

Operation of slice interception:

operationmeaning
s[n]Item with index position n in slice s
s[:]Slice obtained from index position 0 of slice s to len(s)-1
s[low:]Slice obtained from the index position low of slice s to len(s)-1
s[:high]Slice obtained from index position 0 of slice s to high, len=high
s[low:high]The slice obtained from the index position low of slice s to high, len = high low
s[low:high:max]The slice obtained from the index position low of slice s to high, len = high low, cap = max low
len(s)Length of slice s, always < = cap (s)
cap(s)Capacity of slice s, always > = len (s)

demonstration:

func SliceDemo05() {
	slice := []int{1, 2, 3, 4, 5}
	/**
		First value: the starting index of the interception
		Second value: intercepted termination index (excluding this value)
		The third value: used to calculate the capacity of slices. It can be omitted. It is the same as the length by default
		Capacity = third value - first value
		Length = second value - first value
	*/
	newSlice := slice[0:3:3]
	fmt.Println("Cut section", newSlice)
	fmt.Println("Length of slice", len(newSlice))
	fmt.Println("Slice capacity", cap(newSlice))

	// It's the same as copying
	newSlice2 := slice[:]
	fmt.Println("Cut section", newSlice2)
	fmt.Println("Length of slice", len(newSlice2))
	fmt.Println("Slice capacity", cap(newSlice2))
}

Modification of slice value:

After the slice is intercepted, a new slice is returned. Modifying the value of the new slice will affect the original slice

reason:

After the slice is intercepted, the new slice will not be given. The new slice points to the original slice and does not open up a new space for the new slice. Therefore, the new slice operation will affect the original slice

demonstration:

func SliceDemo06() {
	slice := []int{1, 2, 3, 4, 5}
	newSlice2 := slice[0:3]
	fmt.Println("Before slice modification slice Data:", slice) // [1 2 3 4 5]
	newSlice2[0] = 1111
	fmt.Println("After slice modification slice Data:", slice) //[1111 2 3 4 5]
}

append function:

The append function adds data to the end of the slice
If the added content exceeds the capacity initially defined by the slice, the slice will be automatically expanded
The capacity expansion mechanism is: last capacity * 2
If it exceeds 1024 bytes, each expansion is 1 / 4 of the previous one

func SliceDemo07() {
	slice := make([]int, 3, 4)
	// It is defined here that the length of the slice is 3 and the initial capacity is 4. The system will assign a default value to the length. The int type is 0, so three zeros are printed
	fmt.Println(slice) // [0 0 0]

	slice = append(slice, 1)
	// Add data. At this time, the capacity is 4 and there are already 4 data. If you continue to add more data, will an error be reported
	fmt.Println("Add data for the first time:", slice) // [0 0 0 1]

	slice = append(slice, 2, 3, 4, 5, 6, 7, 8, 9)
	fmt.Println("Add data for the second time:", slice) // [0 0 0 1 2 3 4 5 6 7 8 9]
}

copy function:

Assign the data of slice 2 (0 indexed to len-1) to slice 1
Note: if the capacity of slice 1 is insufficient, the remaining data will not be assigned. If slice 1 has more data than slice 2, how much data is copied from slice 2 and how much is copied.
Summary: copy only copies the data corresponding to the index. If the length is not enough, the original data will not be overwritten

Format:

copy(Slice 1,Slice 2)

demonstration:

 // Copy from slice 2 to slice 1, but slice 2 has more data than slice 1. Therefore, only a part of the data corresponding to the index is copied in the end
func SliceDemo08() {
	slice := []int{1, 2, 3}
	slice2 := []int{4, 5, 6, 7, 8, 9}
	copy(slice, slice2)
	fmt.Println(slice) // [4 5 6]
}

 // Copy from slice 1 to slice 1, but the data of slice 1 is less than that of slice 2. Therefore, only a part of the data corresponding to the index is copied in the end
func SliceDemo09() {
	slice := []int{1, 2, 3}
	slice2 := []int{4, 5, 6, 7, 8, 9}
	copy(slice2, slice)
	fmt.Println(slice2) // [1 2 3 7 8 9]
}

Slice as function parameter:

Slice can be used as a parameter of the function, but modifying the value of slice in the function will affect the original slice

demonstration:

func main() {
	//SliceDemo01()
	slice := []int{1, 2, 3, 4, 5}
	SliceDemo10(slice)
}

func SliceDemo10(slice []int) {
	for _, v := range slice {
		fmt.Println(v)
	}
	slice = append(slice, 5, 6, 7)
	fmt.Println(slice) //[1 2 3 4 5 5 6 7]
}

Slice summation:

func main() {
	// Define variables and collect the number of user inputs
	var count int
	fmt.Println("Please enter the number of required and:")
	fmt.Scan(&count)

	// Define the slice and save the entered number to the slice
	slice := make([]int, count)
	statisticalData(slice)

	// Sum
	summation(slice)
}

func statisticalData(slice []int) {
	for i := 0; i < len(slice); i++ {
		fmt.Printf("Please enter page%d number\n", i+1)
		fmt.Scan(&slice[i])
	}
}
func summation(slice []int) {
	var sum int
	for i := 0; i < len(slice); i++ {
		sum += slice[i]
	}
	fmt.Println("And are:", sum)
}

Slice maximum:

func main() {
	// Define variables and collect the number of user inputs
	var count int
	fmt.Println("Please enter the number to compare:")
	fmt.Scan(&count)

	// Define the slice and save the entered number to the slice
	slice := make([]int, count)
	statisticalData(slice)

	// Compare maximum
	maximum(slice)
}

func statisticalData(slice []int) {
	for i := 0; i < len(slice); i++ {
		fmt.Printf("Please enter page%d number\n", i+1)
		fmt.Scan(&slice[i])
	}
}

func maximum(slice []int) {
	max := slice[0]
	for i := 0; i < len(slice); i++ {
		if max < slice[i] {
			max = slice[i]
		}
	}
	fmt.Println("The maximum value is:", max)
}

Topics: Go