当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


GO NewFromFiles用法及代码示例

GO语言"go/doc"包中"NewFromFiles"函数的用法及代码示例。

用法:

func NewFromFiles(fset *token.FileSet, files []*ast.File, importPath string, opts ...any)(*Package, error)

NewFromFiles 计算包的文档。

包由 *ast.Files 列表和相应的文件集指定,不能为 nil。 NewFromFiles 在计算文档时使用所有提供的文件,因此调用者有责任仅提供与所需构建上下文匹配的文件。 "go/build".Context MatchFile 可用于确定文件是否将构建上下文与所需的 GOOS 和 GOARCH 值以及其他构建约束相匹配。包的导入路径由 importPath 指定。

_test.go 文件中的示例根据其名称与相应的类型、函数、方法或包相关联。如果示例名称中有后缀,则在 Example.Suffix 字段中设置。名称格式错误的示例将被跳过。

可选地,可以提供一个 Mode 类型的额外参数来控制文档提取行为的低级方面。

NewFromFiles 拥有 AST 文件的所有权并可以编辑它们,除非 PreserveAST 模式位打开。

例子:

此示例说明了如何使用NewFromFiles 来计算包文档和示例。

package main

import (
    "fmt"
    "go/ast"
    "go/doc"
    "go/parser"
    "go/token"
)

func main() {
    // src and test are two source files that make up
    // a package whose documentation will be computed.
    const src = `
// This is the package comment.
package p

import "fmt"

// This comment is associated with the Greet function.
func Greet(who string) {
    fmt.Printf("Hello, %s!\n", who)
}
`
    const test = `
package p_test

// This comment is associated with the ExampleGreet_world example.
func ExampleGreet_world() {
    Greet("world")
}
`

    // Create the AST by parsing src and test.
    fset := token.NewFileSet()
    files := []*ast.File{
        mustParse(fset, "src.go", src),
        mustParse(fset, "src_test.go", test),
    }

    // Compute package documentation with examples.
    p, err := doc.NewFromFiles(fset, files, "example.com/p")
    if err != nil {
        panic(err)
    }

    fmt.Printf("package %s - %s", p.Name, p.Doc)
    fmt.Printf("func %s - %s", p.Funcs[0].Name, p.Funcs[0].Doc)
    fmt.Printf(" ⤷ example with suffix %q - %s", p.Funcs[0].Examples[0].Suffix, p.Funcs[0].Examples[0].Doc)

}

func mustParse(fset *token.FileSet, filename, src string) *ast.File {
    f, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
    if err != nil {
        panic(err)
    }
    return f
}

输出:

package p - This is the package comment.
func Greet - This comment is associated with the Greet function.
 ⤷ example with suffix "world" - This comment is associated with the ExampleGreet_world example.

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 NewFromFiles。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。