在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/