package main import ( "fmt" ) //清空切面元素 func CleanSlice() { //方法一 通過 切片賦值 方式 清空 var Cslice []int = []int{1, 2, 3} fmt.Printf("清空前元素>>:\n") fmt.Printf("len:%v\tceanslice:%v\n", len(Cslice), Cslice) Cslice = Cslice[0:0] fmt.Printf("清空后元素>>:\n") fmt.Printf("len:%v\tceanslice:%v\n", len(Cslice), Cslice) } //刪除指定的索引元素 func DelIndex() { var DelIndex []int DelIndex = make([]int, 5) DelIndex[0] = 0 DelIndex[1] = 1 DelIndex[2] = 2 DelIndex[3] = 3 DelIndex[4] = 4 fmt.Println("刪除指定索引(下標)前>>:") fmt.Printf("len:%v\tDelIndex:%v\n", len(DelIndex), DelIndex) //刪除元素 3 索引(下標) 3 index := 3 //這里通過 append 方法 分成兩個然后合並 // append(切片名,追加的元素) 切片名這里我們進行切割一個新的切片DelIndex[:index] 追加的元素將索引后面的元素追加 // DelIndex[index+1:]...) 為什么追加會有...三個點, 因為是一個切片 所以需要展開 DelIndex = append(DelIndex[:index], DelIndex[index+1:]...) fmt.Printf("len:%v\tDelIndex:%v\n", len(DelIndex), DelIndex) } func main() { CleanSlice() fmt.Println() DelIndex() }
切片的反轉 reverse
package main import "fmt" func reverse1(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func reverse2(s []int) { for i := 0; i < len(s)/2; i++ { s[i], s[len(s)-i-1] = s[len(s)-i-1], s[i] } } func main() { var s []int = []int{1, 2, 3} reverse1(s) fmt.Printf("s:%v\n", s) fmt.Println() reverse2(s) fmt.Printf("s:%v\n", s) }