英文:
How to copy array into part of another in Go?
问题
我是Go的新手,想要将一个数组(切片)复制到另一个数组的一部分。例如,我有一个largeArray [1000]byte或者其他什么类型的数组,还有一个smallArray [10]byte,我想要largeArray的前10个字节等于smallArray的内容。我尝试过:
largeArray[0:10] = smallArray[:]
但是似乎不起作用。是否有内置的类似memcpy的函数,还是我只能自己编写一个?
谢谢!
英文:
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
得分: 40
使用内置函数copy。
package main
func main() {
largeArray := make([]byte, 1000)
smallArray := make([]byte, 10)
copy(largeArray[0:10], smallArray[:])
}
英文:
Use the copy built-in function.
package main
func main() {
largeArray := make([]byte, 1000)
smallArray := make([]byte, 10)
copy(largeArray[0:10], smallArray[:])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论