golang学习,切片操作。
/**
将一个切片从start位置开始,删除length个元素
*/
func removeStringSlice(slice []string, start, length int) []string {
if ( start + length ) > len(slice) {
panic("越界")
}
return append( slice[:start], slice[start+length:]... )
}
将切片s1插入到s2的指定位置 index处
func insertIntSlice(s1, slice []int, index int) []int {
return append( slice[:index] , append(s1,slice[index:]...)... )
}
/**
将切片s1插入到s2的指定位置 index处
*/
func insertStringSlice(s1, s2 []int, index int) []int {
if index > len(s2){
panic("位置不存在")
}
//将目标切片按照指定位置分为两个临时切片
tmp1 := s2[:index]
tmp2 := s2[index:]
//创建一个长度为s1+s2的切片用于存储两个切片的值
newTmp := make([]int, len(s2)+len(s1))
//重组切片
copy(newTmp, tmp1)
copy(newTmp[index:len(s1)+index], s1)
copy(newTmp[len(newTmp)-len(tmp2):], tmp2)
return newTmp
}
func main(){
slice := []string{"a","b","c","d","e","f","g"}
resRemoveString := removeStringSlice(slice,1,4)
fmt.Println(resRemoveString)
s2 := []int{1,2,3,4,5}
s1 := []int{33,22,11}
resInsert := insertIntSlice(s1,s2,4)
fmt.Println(resInsert)
ss1 := []int{1,2,3,4,5}
ss2 := []int{10,20,30,40,50}
index := 2
ss2 = insertStringSlice(ss1, ss2, index)
fmt.Println(ss2)
}
运行结果
[a f g]
[1 2 3 4 33 22 11 5]
[10 20 1 2 3 4 5 30 40 50]
有疑问加站长微信联系(非本文作者)