题解 | #切片复制#

切片复制

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

全部评论

相关推荐

爱吃烤肠的牛油最喜欢...:50K是ssp了估计,ssp的人家多厉害都不用说,每年比例大概在百分之5左右
点赞 评论 收藏
分享
评论
13
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务