go 切片的 插入删除
Posted 让我们忘了那片海
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go 切片的 插入删除相关的知识,希望对你有一定的参考价值。
package main
import (
"fmt"
)
func InsertSpringSliceCopy(slice, insertion []string, index int) []string {
result :=make([]string, len(slice)+len(insertion))
at := copy(result, slice[:index])
at += copy(result[at:], insertion)
copy(result[at:], slice[index:])
return result
}
func InsertSpringSlice(slice, insertion []string, index int) []string {
return append(slice[:index], append(insertion, slice[index:]...)...)
}
func RemoveSpringSliceCopy(slice []string, start,end int) []string {
result := make([]string, len(slice)-(end-start))
at :=copy(result, slice[:start])
copy(result[at:], slice[end:])
return result
}
func RemoveSpringSlice(slice []string, start, end int) []string {
return append(slice[:start], slice[end:]...)
}
func main() {
s := []string{"C", "H", "A", "O"}
x := InsertSpringSliceCopy(s, []string{"a", "b", "c"}, 0)
fmt.Println(x)
w := []string {"C", "H", "E", "N"}
ww :=InsertSpringSlice(w, []string{"c", "h", "a", "o"}, len(w))
fmt.Println(ww)
d := []string {"a", "b", "c", "d", "e", "f"}
dd := RemoveSpringSliceCopy(d, 2, 4)
fmt.Println(dd)
d2 := []string {"A", "B", "C", "D", "E", "F", "G"}
dd2 := RemoveSpringSlice(d2, 2, 4)
fmt.Println(dd2)
}
以上是关于go 切片的 插入删除的主要内容,如果未能解决你的问题,请参考以下文章