In Go, you can initialise a byte slice as follows (try it on Go Playground)
package main
import (
"fmt"
"encoding/hex"
)
// doStuff will be called many times in actual application, so we want this to be efficient
func doStuff() {
transparentGif := []byte("GIF89a\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff" +
"\xff\xff\xff\x21\xf9\x04\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00" +
"\x01\x00\x01\x00\x00\x02\x02\x4c\x01\x00\x3b\x00")
// This will be returned by a web service in actuality, but here we just hex dump it
fmt.Printf("Your gif is\n%s\n", hex.Dump(transparentGif))
}
func main() {
doStuff()
}
In this case, the data does not need to change, so it would have been nicer (and hopefully more efficient) to initialise it as a constant, near to the function it actually gets used in.
However, as this question makes clear, there is no such thing as a const slice in Go.
Is there a more efficient way to do this while keeping the scope small? Ideally with the concatenation and memory allocation done once only.
As far as I know, I'd have to create the slice outside of the function scope then pass it in as a parameter, i.e. widen the scope.