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!
The Array. Copy() method in C# is used to copy section of one array to another array. Array. Copy(src, dest, length);
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.
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.
Use the copy built-in function.
package main
func main() {
largeArray := make([]byte, 1000)
smallArray := make([]byte, 10)
copy(largeArray[0:10], smallArray[:])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With