首页 > 代码库 > go 切片的 插入、删除

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 切片的 插入、删除