copy(切片间复制)
@
1. 作用
复制切片的值给另一个切片
2. 语法
func copy(dst []Type, src []Type) int
3. 完整示例(切片=》切片)
- 代码
package main
import "fmt"
func main () {
nameList := make([]string,3)
nameList[0] = "刘备"
nameList[1] = "关羽"
nameList[2] = "张飞"
nameList2 := make([]string,2)
copy(nameList2, nameList)
fmt.Println(nameList2)
}
- 结果
[刘备 关羽 张飞]
3. 完整示例(源切片长度 > 目标切片长度)
- 代码
package main
import "fmt"
func main () {
nameList := make([]string,3)
nameList[0] = "刘备"
nameList[1] = "关羽"
nameList[2] = "张飞"
nameList2 := make([]string,2,3)
copy(nameList2, nameList)
fmt.Println(nameList2)
}
- 结果
[刘备 关羽]
如上可见,当 源切片长度(3) > 目标切片长度(2) 时,即使没有超过目标切片容量(3),依然只会复制目标长度的成员数(2)。