copy ---- 数组,切片

package main

import (
    "fmt"
)

func main() {

    data := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}                 // 数组 与 切片 结果一致
    // data := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println("array data : ", data)          // [0 1 2 3 4 5 6 7 8 9]
    s1 := data[8:]
    s2 := data[:5]
    fmt.Printf("slice s1 : %v
", s1)           // [8 9]     
    fmt.Printf("slice s2 : %v
", s2)           // [0 1 2 3 4]

    // copy(s2, s1)
    // fmt.Printf("copied slice s1 : %v
", s1)    // [8 9]
    // fmt.Printf("copied slice s2 : %v
", s2)    // [8 9 2 3 4]
    // fmt.Println("last array data : ", data)     // [8 9 2 3 4 5 6 7 8 9]

    copy(s1, s2)
    fmt.Printf("copied slice s1 : %v
", s1)    // [0 1]
    fmt.Printf("copied slice s2 : %v
", s2)    // [8 9 2 3 4]
    fmt.Println("last array data : ", data)     // [8 9 2 3 4 5 6 7 8 9]

    fmt.Printf("%p",&data[0])                   // 0xc04207e000
    fmt.Println()
    fmt.Printf("%p",&s2[0])                     // 0xc04207e000

}

数组 与 切片,结果一致

copy(a,b) ,将b赋值给a,拷贝多少个元素,取决于元素最少的,有几个,拷贝几个

copy,与值类型或者引用类型无关,都是修改的原数据

当代码中出现 := 时,返回结果不一致,原因待确定

package main

import (
    "fmt"
)

func main() {

    data1 := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}                 // 数组 与 切片 结果一致
    // data1 := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

    data := data1

    fmt.Println("array data : ", data)          // [0 1 2 3 4 5 6 7 8 9]
    s1 := data[8:]
    s2 := data[:5]
    fmt.Printf("slice s1 : %v
", s1)           // [8 9]     
    fmt.Printf("slice s2 : %v
", s2)           // [0 1 2 3 4]

    copy(s2, s1)
    fmt.Printf("copied slice s1 : %v
", s1)    // [8 9]
    fmt.Printf("copied slice s2 : %v
", s2)    // [8 9 2 3 4]
    fmt.Println("last array data : ", data)     // [8 9 2 3 4 5 6 7 8 9]

    // copy(s1, s2)
    // fmt.Printf("copied slice s1 : %v
", s1)    // [0 1]
    // fmt.Printf("copied slice s2 : %v
", s2)    // [0 1 2 3 4]
    // fmt.Println("last array data : ", data)     // [0 1 2 3 4 5 6 7 0 1]

    fmt.Printf("%p",&data[0])                   // 0xc04207e000
    fmt.Println()
    fmt.Printf("%p",&s2[0])                     // 0xc04207e000

}
原因,待确定