Go中切片的复制功能是如何实现的?

问题描述 投票:0回答:2

我想了解go的复制功能如何用于切片

package main

import "fmt"

func main() {

    arr := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

    copy(arr[4:], arr[2:])

    fmt.Println(arr)
}

我预计输出为 [1, 2, 3, 4, 3, 4, 3, 4, 3, 4]

但它是 [1, 2, 3, 4, 3, 4 , 5, 6, 7, 8]

我想知道它(即复制)是如何实现的??

go slice
2个回答
0
投票

copy
会将
min(len(source), len(target))
字节复制到目标。如果区域重叠,
copy
可能会向后工作以避免重新复制已复制的部分。在您的情况下,它将从源的最后一个元素开始向后复制。在其他情况下,它可能会继续复制。


0
投票

我认为这些东西可以帮助你

  1. 复制功能如何运作?

  2. 复制()的评论

// The copy built-in function copies elements from a source slice into a
// 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

copy(arr[4:], arr[2:])
情况下,src和dst重叠。

所以,min (len(arr[4:]), len(arr[2:])) 是 7。

从第二个元素(从零开始的索引

3, 4, 5, 6, 7, 8
)开始的 7 个元素被复制到第 4 个和第 9 个元素之间。

所以结果是

[1, 2, 3, 4, 3, 4 , 5, 6, 7, 8]

如果你想知道它的实现,你可以找到运行时源目录的 memmove 文件,这些文件是用 Assembly 编写的。 (Golang的内置函数实现)

© www.soinside.com 2019 - 2024. All rights reserved.