Home > Article > Backend Development > How to delete array elements in golang (two methods)
Directory:
1. Background
2. Basics of golang array
1. 切片删除 2. 数组拷贝删除
//定义一个长度为3的int型数组 var arr [3]int // 赋值 arr[0] = 1 arr[1] = 2 arr[2] = 3 // 取值 fmt.Println(arr[0],arr[1],arr[2]) // 输出:1 2 33. Golang array deletion methodIn golang, although the array is a container, Because of its fixed-length nature, we cannot directly delete an element in the array. So in practical applications, we can delete elements in the array through the following two methods:
//定义一个长度为3的int型数组 var arr = [3]int{1, 2, 3} // 将数组转换成切片,进行删除 slice := arr[:] deleteIndex := 1 if len(slice) > deleteIndex { slice = append(slice[:deleteIndex], slice[deleteIndex+1:]...) fmt.Println(slice) } // 输出:[1 3]In the above code, we first convert the array into a slice, then specify the subscript to be deleted, and delete the deleted elements from the slice through the append function. Finally print out the deleted slices.
//定义一个长度为3的int型数组 var arr = [3]int{1, 2, 3} // 拷贝删除 deleteIndex := 1 if len(arr) > deleteIndex { arr = append(arr[:deleteIndex], arr[deleteIndex+1:]...) fmt.Println(arr) } // 输出 :[1 3 0]In the above code, we also specify the subscript to be deleted, and then delete the element to be deleted from the array through the append function. The difference is that we directly reassign the deleted array to the original array. 4. SummaryThrough the above two methods, we can easily delete golang array elements. Slice deletion facilitates code writing, while array copy deletion allows direct manipulation of the original array. In actual development, we can flexibly use the two methods as needed.
The above is the detailed content of How to delete array elements in golang (two methods). For more information, please follow other related articles on the PHP Chinese website!