Go內建函數copy:
func copy(dst, src []Type) int
用於將源slice的數據(第二個參數),復制到目標slice(第一個參數)。
返回值為拷貝了的數據個數,是len(dst)和len(src)中的最小值。
看代碼:
package main import ( "fmt" ) func main() { var a = []int{0, 1, 2, 3, 4, 5, 6, 7} var s = make([]int, 6) //源長度為8,目標為6,只會復制前6個 n1 := copy(s, a) fmt.Println("s - ", s) fmt.Println("n1 - ", n1) //源長為7,目標為6,復制索引1到6 n2 := copy(s, a[1:]) fmt.Println("s - ", s) fmt.Println("n2 - ", n2) //源長為8-5=3,只會復制3個值,目標中的后三個值不會變 n3 := copy(s, a[5:]) fmt.Println("s - ", s) fmt.Println("n3 - ", n3) //將源中的索引5,6,7復制到目標中的索引3,4,5 n4 := copy(s[3:], a[5:]) fmt.Println("s - ", s) fmt.Println("n4 - ", n4) }
執行結果:
s - [0 1 2 3 4 5]
n1 - 6
s - [1 2 3 4 5 6]
n2 - 6
s - [5 6 7 4 5 6]
n3 - 3
s - [5 6 7 5 6 7]
n4 - 3