golang-切片copy

2019-05-30 13:15:17 浏览数 (1)

代码语言:javascript复制
package main

import (
    "fmt"
)

func main() {
    fmt.Println("-------------")
    data := []int{1,2,3,5,3,6,2,3}
    s1 := data[6:]//23
    s2 := data[:3]//123
    fmt.Println(s1)
    fmt.Println(s2)
    copy(s2,s1)//目标切片,源切片,对应位置拷贝

    fmt.Println(s2)//[2 3 3]
}
/*
-------------
[2 3]
[1 2 3]
[2 3 3]
 */
代码语言:javascript复制
package main

import (
    "fmt"
)

func remove(data []int, idx int) []int {
    copy(data[idx:], data[idx 1:])//目标地址,源地址
    return data[:len(data)-1]
}

func main()  {
    data := []int{5, 6, 7, 8, 9}  // {5, 6, 8, 9, 9}
    fmt.Println(data[3:])
    afterData := remove(data, 2)

    fmt.Println("afterData:", afterData)
}
/*
[8 9]
afterData: [5 6 8 9]

 */

0 人点赞