在Go中,您可以如下初始化字节片(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()
}
在这种情况下,数据不需要更改,因此将其初始化为一个常量,接近其实际使用的功能会更好(并且希望更有效)。
但是,正如[C0]所表明的那样,Go中没有诸如const slice这样的东西。
在保持范围较小的同时,还有一种更有效的方法吗?理想情况下,连接和内存分配仅执行一次。
据我所知,我必须在功能范围之外创建切片,然后将其作为参数传递,即扩大范围。
在Go中,您可以如下初始化字节片(在Go Playground上尝试)包main import(“ fmt”“ encoding / hex”)// doStuff在实际应用中将被调用很多次,所以我们...
将this question声明为包级变量,然后在函数中使用该变量。