简体   繁体   中英

Best way to init an unchanging byte slice

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, ie widen the scope.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM