Home > Mobile >  Trying to understand how to rename a byte array in Go
Trying to understand how to rename a byte array in Go

Time:12-09

I'm trying to reassign a byte array based on conditional logic. I don't understand my options. Here's the code:

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...

I need to have outBuffer be the same kind of thing as s3Buffer, a byte array containing the contents of the s3 object I've downloaded. The copy command seems illogical, but more straightforward. I've been reading Go tutorials for a few days but I can't find clarity on this. I'm very new to Go so I might be doing something terribly wrong here, I acknowledge.

CodePudding user response:

outBuffer = s3Buffer will copy the slice header, but not the actual data. This is the fastest and is totally fine, just know that after this assignment both variables will point to the same data, so modifying the data via any of them would be reflected on the other. See 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()`?

As an alternative to copy(), you could use the builtin append() function. It appends elements to a slice, elements which may be elements of another slice; but–unlike copy()append() takes care of space allocation when needed. It would look like:

outBuffer = append(outBuffer, s3Buffer...)

Read blog posts to learn more about slices:

Go Slices: usage and internals

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

  • Related