在 Go 中,您可以按如下方式初始化字节切片(在 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()
}
在这种情况下,数据不需要更改,因此将其初始化为常量,靠近实际使用的函数会更好(并且希望更有效)。
然而,Go 中不存在 const 切片这样的东西。
有没有更有效的方法来做到这一点,同时保持较小的范围?理想情况下,串联和内存分配仅完成一次。
据我所知,我必须在函数作用域之外创建切片,然后将其作为参数传递,即扩大作用域。
慕仙森
相关分类