猿问

初始化不变字节片的最佳方法

在 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 切片这样的东西。

有没有更有效的方法来做到这一点,同时保持较小的范围?理想情况下,串联和内存分配仅完成一次。

据我所知,我必须在函数作用域之外创建切片,然后将其作为参数传递,即扩大作用域。


婷婷同学_
浏览 108回答 1
1回答

慕仙森

声明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如果按照问题中的建议添加参数,则调用者将被迫了解此详细信息。
随时随地看视频慕课网APP

相关分类

Go
我要回答