Introduction
A .go file holds source code in Go, the
compiled language created at Google. The go command builds all the
.go files in a folder together as one package, and a go.mod
file at the top of a project names the module and the versions of its
dependencies.
Files whose names end in _test.go hold tests and are only compiled by
go test.
Structure
A Go source file is plain UTF-8 text. It must start, after any comments, with a
package clause naming its package; every file in a folder belongs to the
same package, and a program’s entry point is the main function of package
main. Then come the import declarations and the file’s
functions, types, constants and variables.
A //go:build line before the package clause limits the file to certain
systems or build tags. Layout is standardised by the gofmt tool, which
indents with tabs, so most Go code looks the same.
package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}
Links
Software
- Go, with the
gocommand andgofmt(Windows, macOS, Linux) - Visual Studio Code (Windows, macOS, Linux)
- GoLand (Windows, macOS, Linux)
- Vim (Windows, macOS, Linux)
Developers
- go/parser and go/ast, Go’s own packages for parsing Go source
- tree-sitter-go, Go grammar for the Tree-sitter parser used by editors