go切片复制 copy()

一、语法 【go切片复制 copy()】go语言的内置函数 copy() 可以将一个数组切片复制到另一个数组切片中,如果加入的两个数组切片不一样大,就会按照其中较小的那个数组切片的元素个数进行复制。
func copy(dst, src []Type) int
使用copy有几个特征

  1. 如果之前是两个不同的地址,copy后也是两个不同的地址,改变其中一个不影响另一个。
  2. copy到目标slice,到底复制多少,取决于它的大小以及起始位置。
二、使用示范 1、同样的大小
go切片复制 copy()
文章图片

func TestCopy1(t *testing.T) { from := []int{1, 2, 3} var to []int = make([]int, len(from), cap(from)) t.Logf("from slice: %[1]v, address: %[1]p\n", from) t.Logf("to slice: %[1]v, address: %[1]p\n", to)copy(to, from) t.Log("copy(to, from)后:") t.Logf("from slice: %[1]v, address: %[1]p\n", from) t.Logf("to slice: %[1]v, address: %[1]p\n", to)to[0] = 11 t.Log("to[0] = 11后:") t.Logf("from slice: %[1]v, address: %[1]p\n", from) t.Logf("to slice: %[1]v, address: %[1]p\n", to) }

输出:
from slice: [1 2 3], address: 0xc0000cc060 to slice: [0 0 0], address: 0xc0000cc080 copy(to[2:], from)后: from slice: [1 2 3], address: 0xc0000cc060 to slice: [1 2 3], address: 0xc0000cc080 to[0] = 11后: from slice: [1 2 3], address: 0xc0000cc060 to slice: [11 2 3], address: 0xc0000cc080

2、目标的slice为长度len为0的时候,复制不成功,还是为空[]
go切片复制 copy()
文章图片

func TestCopy2(t *testing.T) { from := []int{1, 2, 3} var to []int = make([]int, 0, cap(from)) t.Logf("from slice: %[1]v, address: %[1]p\n", from) t.Logf("to slice: %[1]v, address: %[1]p\n", to)copy(to, from) t.Log("copy(to, from)后:") t.Logf("from slice: %[1]v, address: %[1]p\n", from) t.Logf("to slice: %[1]v, address: %[1]p\n", to) }

输出:
from slice: [1 2 3], address: 0xc000144060 to slice: [], address: 0xc000144080 copy(to, from)后: from slice: [1 2 3], address: 0xc000144060 to slice: [], address: 0xc000144080

3、目标的slice为长度len为1的时候,只能复制第一个
go切片复制 copy()
文章图片

func TestCopy3(t *testing.T) { from := []int{1, 2, 3} var to []int = make([]int, 1, cap(from)) t.Logf("from slice: %[1]v, address: %[1]p\n", from) t.Logf("to slice: %[1]v, address: %[1]p\n", to)copy(to, from) t.Log("copy(to, from)后:") t.Logf("from slice: %[1]v, address: %[1]p\n", from) t.Logf("to slice: %[1]v, address: %[1]p\n", to) }

输出:
from slice: [1 2 3], address: 0xc0000cc060 to slice: [0], address: 0xc0000cc080 copy(to, from)后: from slice: [1 2 3], address: 0xc0000cc060 to slice: [1], address: 0xc0000cc080

    推荐阅读