如何在Go中将数组复制到另一个数组的一部分?

huangapple go评论116阅读模式
英文:

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[:])
}

huangapple
  • 本文由 发表于 2011年8月31日 14:03:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/7253152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定