Reputation: 91
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
.
Upvotes: 1
Views: 478
Reputation: 417612
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 Why can't I duplicate a slice with `copy()`?).
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:])
Upvotes: 8