doc: update docs/golang.md (#359)

This commit is contained in:
MarioMang 2023-04-25 18:55:28 +08:00 committed by GitHub
parent dd53261d3c
commit 1aae2c027e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 103 additions and 1 deletions

View File

@ -163,7 +163,7 @@ Quick Reference
[Zip](./docs/zip.md)<!--rehype:style=background: rgb(99 99 99);--> [Zip](./docs/zip.md)<!--rehype:style=background: rgb(99 99 99);-->
[APT](./docs/apt.md)<!--rehype:style=background: rgb(30 144 255);--> [APT](./docs/apt.md)<!--rehype:style=background: rgb(30 144 255);-->
[tar](./docs/tar.md)<!--rehype:style=background: rgb(215 89 62);--> [tar](./docs/tar.md)<!--rehype:style=background: rgb(215 89 62);-->
[pacman](./docs/pacman.md)<!--rehype:style=background: rgb(24 147 209);&class=tag&data-lang=archlinux&class=contributing--> [pacman](./docs/pacman.md)<!--rehype:style=background: rgb(24 147 209);&class=tag&data-lang=archlinux&class=contributing-->
[Linux Command](./docs/linux-command.md)<!--rehype:style=background: rgb(215 89 62);&class=tag&data-lang=命令速查--> [Linux Command](./docs/linux-command.md)<!--rehype:style=background: rgb(215 89 62);&class=tag&data-lang=命令速查-->
<!--rehype:class=home-card--> <!--rehype:class=home-card-->

View File

@ -1028,6 +1028,108 @@ func main() {
``` ```
<!--rehype:className=wrap-text --> <!--rehype:className=wrap-text -->
Golang Embed
---
### 嵌入为string
``` go
package main
import (
_ "embed"
"fmt"
)
//go:embed version.txt
var version string
func main() {
fmt.Printf("version %q\n", version)
}
```
### 嵌入为[]byte
``` go
package main
import (
_ "embed"
"fmt"
)
//go:embed version.txt
var versionByte []byte
func main() {
fmt.Printf("version %q\n", string(versionByte))
}
```
### 嵌入为embed.FS
``` go
//go:embed hello.txt
var f embed.FS
func main() {
data, _ := f.ReadFile("hello.txt")
fmt.Println(string(data))
}
```
### 嵌入多个文件
``` go
//go:embed hello.txt
//go:embed hello2.txt
var f embed.FS
func main() {
data, _ := f.ReadFile("hello.txt")
fmt.Println(string(data))
data, _ = f.ReadFile("hello2.txt")
fmt.Println(string(data))
}
```
### 嵌入子文件夹下的文件
``` go
//go:embed p/hello.txt p/hello2.txt
var f embed.FS
func main() {
data, _ := f.ReadFile("p/hello.txt")
fmt.Println(string(data))
data, _ = f.ReadFile("p/hello2.txt")
fmt.Println(string(data))
}
```
### 同一个文件嵌入为多个变量
``` go
//go:embed hello.txt
var s string
//go:embed hello.txt
var s2 string
func main() {
fmt.Println(s)
fmt.Println(s2)
}
```
### 匹配模式
``` go
//go:embed p/*
var f embed.FS
func main() {
data, _ := f.ReadFile("p/.hello.txt")
fmt.Println(string(data))
data, _ = f.ReadFile("p/q/.hi.txt") // 没有嵌入 p/q/.hi.txt
fmt.Println(string(data))
}
```
杂项 杂项
------------- -------------