Compiler directives
- Go course
- Expert
- Lesson 17/34
- 4 min
Learn directives like //go:nosplit.
Compiler directives
Comments starting with //go: are instructions to the compiler (no space in between). Common ones:
//go:noinline— don't inline.//go:build linux— compile the file only under this condition.//go:embed— embed a file in the binary.//go:generate— a command run bygo generate.//go:nosplit,//go:noescape— low-level directives for the runtime and assembly.
go:embed and go:build
With the embed package files go into the binary at build time; they don't need to be on disk at run time:
import _ "embed"
//go:embed surum.txt
var surum stringBuild constraints go at the top of the file: //go:build linux && amd64. File name suffixes such as _linux.go and _test.go add similar constraints.
Practice Embedded file system
Try the embed idea without a disk file: create a file system with testing/fstest.MapFS where "surum.txt" contains "1.4.0", then read it with fs.ReadFile and print it.
Starter code
package main
import (
"fmt"
"io/fs"
"testing/fstest"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"io/fs"
"testing/fstest"
)
func main() {
fsys := fstest.MapFS{"surum.txt": {Data: []byte("1.4.0")}}
b, err := fs.ReadFile(fsys, "surum.txt")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}Expected output
1.4.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you write <code>// go:noinline</code> (with a space)?
- It works the same
- It fails to compile
- The function is deleted
- It counts as an ordinary comment and has no effect Correct answer
Explanation: Directives must start exactly with //go:; the spaced version is ignored by the compiler.
2 Build constraint
//go:____ !windows
package main
//go:build !windows
package main
Explanation: The //go:build line sets under which OS/architecture condition the file is compiled.
3 Directive and effect
| Term | Meaning |
|---|---|
//go:build |
Conditional compilation |
//go:embed |
Embed a file |
//go:generate |
Code generation command |
//go:noinline |
Don't inline |