0

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.

tuck1s
  • 1,002
  • 9
  • 28
  • 4
    The answer to the same question you linked says you may create a _variable_ of slice type. Isn't that a good fit for you? – icza Oct 14 '19 at 12:37

1 Answers1

1

Declare transparentGif as a package-level variable and use that variable in the function.

var 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")

func doStuff() {
    fmt.Printf("Your gif is\n%s\n", hex.Dump(transparentGif))
}

This does add a declaration to the package scope, but is otherwise neat and tidy. Callers of doStuff are forced to know about this detail if an argument is added as suggested in the question.

  • Excellent, thank you! Implied in your answer, but perhaps worth calling out specifically - that the `var` construct works within package scope. The `:=` style does _not_ work in package scope. – tuck1s Oct 14 '19 at 14:56