开发者

How to copy array into part of another in Go?

开发者 https://www.devze.com 2023-03-31 18:06 出处:网络
I 开发者_Python百科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 1

I 开发者_Python百科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!


Use the copy built-in function.

package main

func main() {
    largeArray := make([]byte, 1000)
    smallArray := make([]byte, 10)
    copy(largeArray[0:10], smallArray[:])
}
0

精彩评论

暂无评论...
验证码 换一张
取 消