在 Go 中,您可以按如下方式初始化字節切片(在 Go Playground 上嘗試)package mainimport (? ? "fmt"? ? "encoding/hex")// doStuff will be called many times in actual application, so we want this to be efficientfunc 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 切片這樣的東西。有沒有更有效的方法來做到這一點,同時保持較小的范圍?理想情況下,串聯和內存分配僅完成一次。據我所知,我必須在函數作用域之外創建切片,然后將其作為參數傳遞,即擴大作用域。
1 回答

慕仙森
TA貢獻1827條經驗 獲得超8個贊
聲明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如果按照問題中的建議添加參數,則調用者將被迫了解此詳細信息。
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報
0/150
提交
取消