试图了解如何在 Go 中重命名字节数组

Trying to understand how to rename a byte array in Go

我正在尝试根据条件逻辑重新分配一个字节数组。我不明白我的选择。这是代码:

s3Buffer, numBytes, err :=  DownloadS3File(event.S3Bucket, event.S3ObjectID, session)

header, err = GetHeader(s3Buffer)

var outBuffer []byte

if HeaderIndicatesConversionNeeded(header) {
    outBuffer, err = ConvertBuffer(s3Buffer, event.ObjectID)
} else {
    // outBuffer = s3Buffer or copy(outBuffer, s3Buffer) or outBuffer = *s3Buffer or ??
}

// use outBuffer...

我需要让 outBuffer 成为与 s3Buffer 相同的东西,一个包含我下载的 s3 对象内容的字节数组。复制命令似乎不合逻辑,但更直接。几天来我一直在阅读 Go 教程,但我无法弄清楚这一点。我是 Go 的新手,所以我可能在这里做错了,我承认。

outBuffer = s3Buffer 将复制切片 header,但不会复制实际数据。这是最快的并且完全没问题,只要知道在这个赋值之后两个变量将指向相同的数据,因此通过其中任何一个修改数据都会反映在另一个上。参见 Are slices passed by value?

copy() is useful if you want to "detach" one slice from another. Note that copy() also needs you to preallocate the destination slice, as it copies no more that what's available in the source and what can be copied to the destination (it copies the minimum of len(src) and len(dst)). For details, see Why can't I duplicate a slice with `copy()`?

作为 copy() 的替代方法,您可以使用内置的 append() 函数。它将元素附加到一个切片,这些元素可能是另一个切片的元素;但是——不像 copy()append() 在需要时负责 space 分配。它看起来像:

outBuffer = append(outBuffer, s3Buffer...)

阅读博文以了解有关切片的更多信息:

Go Slices: usage and internals

Arrays, slices (and strings): The mechanics of 'append'