英文:
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_Position
到source_Position + length - 1
的组件将被复制到目标数组,从destination_Position
到destination_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:])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论