Standard library / go/doc
go/doc.NewFromFiles()
Extracts package documentation from caller-selected parsed files; PreserveAST avoids mutation. Expected stdout: 'demo Answer\n'.
Formal Syntax & Structure
go syntaxgo
func NewFromFiles(fset *token.FileSet, files []*ast.File, importPath string, opts ...any) (*Package, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fset | *token.FileSet | File set used to parse source. |
| files | []*ast.File | Parsed source files belonging to the same package. |
| importPath | string | Input to the operation as described above. |
| opts | ...any | Input to the operation as described above. |
Return Value
(*Package, error)
Extracts package documentation from caller-selected parsed files; PreserveAST avoids mutation.
Working Example
Example Snippetgo
package main
import ( "fmt" "go/ast" "go/doc" "go/parser" "go/token")
func check(e error) { if e != nil { panic(e) }}func packageDoc(mode doc.Mode) *doc.Package { fs := token.NewFileSet() f, e := parser.ParseFile(fs, "demo.go", `// Package demo documents values.package demo// Answer is a number.const Answer=42// hidden is private.var hidden=1// Item describes a value.type Item struct{}// Work performs work.func Work(){}// BUG(user): fix example.`, parser.ParseComments) check(e) p, e := doc.NewFromFiles(fs, []*ast.File{f}, "example.invalid/demo", mode) check(e) return p}
func main() { p := packageDoc(doc.PreserveAST); fmt.Println(p.Name, p.Consts[0].Names[0]) }