import (_ "embed")

实际上接受嵌入文件数据的变量也可以是string和[]byte的类型别名或基于他们定义的新类型,例如下面的代码那样:

type StringAlias = string

//go:embed a.txt
var text1 StringAlias

type NewBytes []byte

//go:embed b.txt
var text2 NewBytes
[]bytestring
package main

import (
    "fmt"
    _ "embed"
)

//go:embed macbeth.txt
var macbeth string

//go:embed texts/en.txt
var hello string

func main() {
    fmt.Println(len(macbeth)) // 麦克白的总字符数
    fmt.Println(hello) // Output: Hello, world
}

再来看看二进制文件的例子,embed_img.go如下所示:

package main

import (
    "fmt"
    _ "embed"
)

//go:embed imgs/screenrecord.gif
var gif []byte

//go:embed imgs/png/a.png
var png []byte

func main() {
    fmt.Println("gif size:", len(gif)) // gif size: 81100466
    fmt.Println("png size:", len(png)) // png size: 4958264
}