猿问

是否可以将外部文件作为字符串常量包含在 go 中?

我一直希望可以在 C++ 中做这样的事情:


const std::string fragmentShader = "

#include "shader.frag"

";

显然这行不通,而且在 C++ 中没有办法做到这一点。但是在 go 中有可能吗?IE


const fragmentShader string = `

<insert contents of shader.frag at compile-time>

`

动机应该很明显!


慕的地10843
浏览 235回答 2
2回答

MMMHUHU

这在纯 Go 中是不可能的。但是,您可以编写一个程序来读取文件并从中创建一个 Go 文件,例如:package mainimport "flag"import "os"import "fmt"import "bufio"import "io"var (&nbsp; &nbsp; packageName = flag.String("p", "main", "package name")&nbsp; &nbsp; outFile&nbsp; &nbsp; &nbsp;= flag.String("o", "-", "output file. Defaults to stdout")&nbsp; &nbsp; varName&nbsp; &nbsp; &nbsp;= flag.String("v", "file", "variable name"))const (&nbsp; &nbsp; header&nbsp; = "package %s\n\nvar %s = [...]byte{\n"&nbsp; &nbsp; trailer = "}\n")func main() {&nbsp; &nbsp; flag.Parse()&nbsp; &nbsp; if len(flag.Args()) != 1 {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintln(os.Stderr, "Please provide exactly one file name")&nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; }&nbsp; &nbsp; var inF, outF *os.File&nbsp; &nbsp; if *outFile == "-" {&nbsp; &nbsp; &nbsp; &nbsp; outF = os.Stdout&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; var err error&nbsp; &nbsp; &nbsp; &nbsp; outF, err = os.Create(*outFile)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(os.Stderr, "Cannot create %s: %v\n", *outFile, err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; inF, err := os.Open(flag.Args()[0])&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(os.Stderr, "Cannot open %s: %v\n", flag.Args()[0], err)&nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; }&nbsp; &nbsp; in, out := bufio.NewReader(inF), bufio.NewWriter(outF)&nbsp; &nbsp; fmt.Fprintf(out, header, *packageName, *varName)&nbsp; &nbsp; buf := make([]byte, 16)&nbsp; &nbsp; var n int&nbsp; &nbsp; for n, err = io.ReadFull(in, buf); n > 0; n, err = io.ReadFull(in, buf) {&nbsp; &nbsp; &nbsp; &nbsp; out.WriteRune('\t')&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < n-1; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(out, "%#02x, ", buf[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(out, "%#02x,\n", buf[n-1])&nbsp; &nbsp; }&nbsp; &nbsp; out.WriteString(trailer)&nbsp; &nbsp; out.Flush()&nbsp; &nbsp; if err != io.EOF {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(os.Stderr, "An error occured while reading from %s: %v\n", flag.Args()[0], err)&nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答