Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy array into part of another in Go?

Tags:

go

I am new to Go, and would like to copy an array (slice) into part of another. For example, I have a largeArray [1000]byte or something and a smallArray [10]byte and I want the first 10 bytes of largeArray to be equal to the contents of smallArray. I have tried:

largeArray[0:10] = smallArray[:]

But that doesn't seem to work. Is there a built-in memcpy-like function, or will I just have to write one myself?

Thanks!

like image 533
fyhuang Avatar asked Aug 31 '11 06:08

fyhuang


People also ask

How do I copy part of an array to another array?

The Array. Copy() method in C# is used to copy section of one array to another array. Array. Copy(src, dest, length);

How do you copy part of an array?

There are multiple ways to copy elements from one array in Java, like you can manually copy elements by using a loop, create a clone of the array, use Arrays. copyOf() method or System. arrayCopy() to start copying elements from one array to another in Java.

How do you copy slices in Go?

To duplicate a slice in Go, getting a deep copy of its contents, you need to either use the built-in copy() function, or create a new empty slice and add all the elements of the first slice to it using the append() function.


1 Answers

Use the copy built-in function.

package main

func main() {
    largeArray := make([]byte, 1000)
    smallArray := make([]byte, 10)
    copy(largeArray[0:10], smallArray[:])
}
like image 161
peterSO Avatar answered Sep 21 '22 01:09

peterSO