1

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.

icza
  • 389,944
  • 63
  • 907
  • 827
Jason Michael
  • 516
  • 5
  • 16

1 Answers1

0

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'

icza
  • 389,944
  • 63
  • 907
  • 827
  • This is what I didn't understand! copy() was leaving me with an empty byte array, presumably because I just declared it, and did not use make() to allocate space. I hope I'm understanding what you're saying. I'll try it! – Jason Michael Dec 08 '21 at 17:13
  • yes! it worked and I learned something! copy() does not allocate the space for the destination buffer. It was silly of me to assume it does. Thanks so much @icza! – Jason Michael Dec 08 '21 at 17:28