Golang Slice 删除指定的索引(下标)和 slice 清空 等常用操作

清空slice所有的元素

package main

import (
	"fmt"
)

//清空切面元素
func CleanSlice() {
	//方法一 通过 切片赋值 方式 清空
	var Cslice []int = []int{1, 2, 3}
	fmt.Printf("清空前元素>>:
")
	fmt.Printf("len:%v	ceanslice:%v
", len(Cslice), Cslice)
	Cslice = Cslice[0:0]
	fmt.Printf("清空后元素>>:
")
	fmt.Printf("len:%v	ceanslice:%v
", len(Cslice), Cslice)
	//方法二 直接通过make 分配内存方式即可
	Cslice = []int{1, 2, 3}
	fmt.Printf("清空前元素>>:
")
	fmt.Printf("len:%v	ceanslice:%v
", len(Cslice), Cslice)
	Cslice=make([]int,0)
	fmt.Printf("清空后元素>>:
")
	fmt.Printf("len:%v	ceanslice:%v
", len(Cslice), Cslice)
}

func main(){
	CleanSlice()
}

Slice删除指定的索引的元素

//删除指定的索引元素
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	DelIndex:%v
", 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	DelIndex:%v
", len(DelIndex), DelIndex)
	fmt.Println("DelIndex:",DelIndex)
}

func main() {
	DelIndex()
}

切片的反转 reverse

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
", s)
	fmt.Println()
	reverse2(s)
	fmt.Printf("s:%v
", s)
}

原文地址:https://www.cnblogs.com/egrep/p/10532806.html