Generate code and extract documentation
Generate code and extract documentation
Code generation is useful for repetitive declarations derived from a well-defined input. A generator should validate identifiers, quote data using Go syntax and format its output. The go generate command executes explicit directives; go build and go test do not automatically run it. Review directives before running a generator from an unfamiliar repository. Prefer deterministic output and the generated-code marker.
package main
import ( "bytes" "fmt" "go/format" "go/token" "text/template")
func generate(name, value string) ([]byte, error) { if !token.IsIdentifier(name) || name == "_" { return nil, fmt.Errorf("invalid name") } var b bytes.Buffer t := template.Must(template.New("go").Parse("// Code generated by demo; DO NOT EDIT.\npackage p\nconst {{.Name}} = {{printf \"%q\" .Value}}\n")) if e := t.Execute(&b, struct{ Name, Value string }{name, value}); e != nil { return nil, e } return format.Source(b.Bytes())}func main() { b, e := generate("Title", "hello\nworld") if e != nil { panic(e) } fmt.Print(string(b)) _, e = generate("for", "x") fmt.Println(e != nil)}The template uses %q for a Go string literal and validates the identifier before interpolation. Arbitrary string concatenation can create invalid or unintended source. In a real module keep generation input and command reproducible, format the bytes before saving, and test compilation after regeneration.
Expected output:
// Code generated by demo; DO NOT EDIT.package p
const Title = "hello\nworld"trueExtract documentation from parsed comments
package main
import ( "fmt" "go/ast" "go/doc" "go/parser" "go/token" "strings")
func main() { fs := token.NewFileSet() f, e := parser.ParseFile(fs, "p.go", `// Package p demonstrates docs.package p// Add adds two numbers.func Add(a,b int)int{return a+b}func hidden(){}`, parser.ParseComments) if e != nil { panic(e) } d, e := doc.NewFromFiles(fs, []*ast.File{f}, "example/p") if e != nil { panic(e) } fmt.Println(strings.TrimSpace(d.Doc)) for _, fn := range d.Funcs { fmt.Println(fn.Name, strings.TrimSpace(fn.Doc)) }}go/doc builds documentation from syntax and comments. The default mode excludes the unexported hidden function. Use the correct build-selected file set for a package; passing every file in a directory may mix incompatible build variants. NewFromFiles may modify the AST unless PreserveAST is requested.
Expected output:
Package p demonstrates docs.Add Add adds two numbers.Try it locally
Generate a declaration for constant Code with value a"b using strconv.Quote, format it and print. Verify the generated text parses.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Developer tooling 05: Generate code and extract documentation
Check the lesson objective before moving on.
When is go generate run automatically by go build?
How should an arbitrary data string become Go source?