21

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!

1
  • 8
    @AnschelSchaffer-Cohen I google'd almost exactly that, and this and a few other like it were listed before the official docs. Also, the docs lack examples to help illustrate how it works (I read the docs first, then came here to finally "get it", and yes, I'm new to Go). Commented Jan 15, 2016 at 18:51

1 Answer 1

41

Use the copy built-in function.

package main

func main() {
    largeArray := make([]byte, 1000)
    smallArray := make([]byte, 10)
    copy(largeArray[0:10], smallArray[:])
}
Sign up to request clarification or add additional context in comments.

5 Comments

Nitpicky remark: the [:] bit in the copy() call is not necessary.
Does it have to be a copy? Slices can be a kind of overlay of arrays or other slices. So smallSlice := largeArray[0:10] would be enough.
@Mue: Yes, the copy is from smallArray to largeArray. You are copying from largeArray to smallSlice [sic].
Isnt't that actually creating two slices, not two arrays? But I guess the same code works for arrays as well
To be strictly correct, it would be this for creating those arrays in that example: var largeArray [1000]byte; var smallArray[10]byte. Note that as indicated, copy can write to a subsection of a slice or array, and I think you can omit the range index on the array because it's copying into 0-9 index of largeArray, copy only copies as much as is contained in the second, and limited by the length (not capacity, I think) of the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.