题解 | #切片复制#
切片复制
http://www.nowcoder.com/practice/007731bde92a4291a2fe10ef2bc57cea
感觉题目不是很合理,空的切片 copy不起作用的 看下面的main 和 他的 输出
import "fmt"
func main1() {
slice1 := []int{1, 2, 3, 4}
slice2 := []int{5, 6}
copy(slice1, slice2)
fmt.Println(slice1)
fmt.Println(slice2)
//[5 6 3 4]
//[5 6]
slice3 := []int{1, 2, 3, 4}
slice4 := []int{5, 6}
copy(slice4, slice3)
fmt.Println(slice3)
fmt.Println(slice4)
//[1 2 3 4]
//[1 2]
//如果有空的呢?
//全是
//[]
//[1 2]
//[]
//[1 2]
slice6 := make([]int, 0, 0)
slice7 := []int{1, 2}
copy(slice6, slice7)
fmt.Println(slice6)
fmt.Println(slice7)
slice8 := make([]int, 0, 0)
slice9 := []int{1, 2}
copy(slice9, slice8)
fmt.Println(slice8)
fmt.Println(slice9)
}
func sliceCopy(src []int, des []int) []int {
// write code here
return src
}
深入源码,看一下:
// destination slice. (As a special case, it also will copy bytes from a
// string to a slice of bytes.) The source and destination may overlap. Copy
// returns the number of elements copied, which will be the minimum of
// len(src) and len(dst).
func copy(dst, src []Type) int
说的很清楚,copied的是 两个长度的最小值,空的切片压根就不会copy
传音控股公司福利 340人发布
查看14道真题和解析