go - 初始化不变的 byte slice 的最佳方法

标签 go constants slice

在Go中,您可以按以下方式初始化 byte slice (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()
}

在这种情况下,数据不需要更改,因此将其初始化为一个常量,接近其实际使用的功能会更好(并且希望更有效)。

但是,正如this question所表明的那样,Go中没有诸如const slice这样的东西。

有没有一种更有效的方式来做到这一点,同时又将范围缩小了?理想情况下,串联和内存分配仅执行一次。

据我所知,我必须在功能范围之外创建 slice ,然后将其作为参数传递,即扩大范围。

最佳答案

transparentGif声明为包级变量,然后在函数中使用该变量。

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))
}

这确实在包范围中添加了一个声明,但是整洁。如果按照问题中的建议添加了参数,则doStuff的调用者将被迫了解此详细信息。

关于go - 初始化不变的 byte slice 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376730/

相关文章:

google-app-engine - Go http包如何发送204 No Content?

arrays - GoLang : Check if item from Slice 1 contains in Slice 2. 如果是,删除 Slice 2

python - 匹配字符串结尾

go - 在 golang 中有 nil slice 和 empty slice 有什么意义?

json - 将yaml转换为不带结构的json

heroku - 非本地包中的本地导入

c++ - Const 静态成员函数 : is another approach available?

c++ - const 使用的内存通常比#define 多还是少?

c++ - 混合 const 和非常量传递引用的参数顺序

go - 不能使用 (type interface{}) 作为类型 []Type