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

NameTypeDescription
fset*token.FileSetFile set used to parse source.
files[]*ast.FileParsed source files belonging to the same package.
importPathstringInput to the operation as described above.
opts...anyInput 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]) }
Go Reference