Go语言中与Java的System.arraycopy()等效的函数是什么?

huangapple go评论92阅读模式
英文:

What's the Go Equivalent of Java's System.arraycopy()?

问题

Java的java.lang.System.arraycopy()是否有Golang的等效方法?

arraycopy(Object source_arr, int sourcePos, Object dest_arr, int destPos, int len)

将源数组从特定起始位置复制到目标数组的指定位置。要复制的参数数量由len参数决定。
source_Positionsource_Position + length - 1的组件将被复制到目标数组,从destination_Positiondestination_Position + length - 1

英文:

Is there any Golang equivalent for Java's java.lang.System.arraycopy()?

arraycopy(Object source_arr, int sourcePos, Object dest_arr, int destPos, int len)

To copy a source array from a specific beginning position to the destination array from the mentioned position. Number of arguments to be copied are decided by len argument.
The components at source_Position to source_Position + length – 1 are copied to destination array from destination_Position to destination_Position + length – 1.

答案1

得分: 8

你可以使用内置的 copy() 函数。

func copy(dst, src []Type) int

它只接受两个参数:目标切片和源切片,但你可以使用 切片表达式 来指定“缺失”的参数,因为 copy() 只会复制源切片中可用的元素数量或适合目标切片的元素数量(参见 https://stackoverflow.com/questions/30182538/why-cant-i-duplicate-a-slice-with-copy/30182622#30182622)。

src := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
dst := make([]int, len(src))

sourcePos := 2
destPos := 3
length := 4

copy(dst[destPos:], src[sourcePos:sourcePos+length])

fmt.Println(dst)

输出结果(在 Go Playground 上尝试):

[0 0 0 2 3 4 5 0 0 0 0]

另一种变体是将 length 添加到 destPos

copy(dst[destPos:destPos+length], src[sourcePos:])
英文:

You may use the builtin copy() function.

func copy(dst, src []Type) int

It only takes 2 arguments: the destination and source slices, but you may use slice expressions to specify the "missing" parameters, because copy() copies no more elements than what's available in the source or what can fit in the destination (see https://stackoverflow.com/questions/30182538/why-cant-i-duplicate-a-slice-with-copy/30182622#30182622).

src := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
dst := make([]int, len(src))

sourcePos := 2
destPos := 3
length := 4

copy(dst[destPos:], src[sourcePos:sourcePos+length])

fmt.Println(dst)

Output (try it on the Go Playground):

[0 0 0 2 3 4 5 0 0 0 0]

Another variant is to add length to the destPos:

copy(dst[destPos:destPos+length], src[sourcePos:])

huangapple
  • 本文由 发表于 2021年12月17日 17:51:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/70391284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定