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.
相關用法
- GO NewReader用法及代碼示例
- GO NewCBCDecrypter用法及代碼示例
- GO NewCFBDecrypter用法及代碼示例
- GO NewCFBEncrypter用法及代碼示例
- GO NewReplacer用法及代碼示例
- GO New用法及代碼示例
- GO NewGCM用法及代碼示例
- GO NewTripleDESCipher用法及代碼示例
- GO NewWriter用法及代碼示例
- GO NewCBCEncrypter用法及代碼示例
- GO NewOFB用法及代碼示例
- GO NewTLSServer用法及代碼示例
- GO NewTicker用法及代碼示例
- GO NewCTR用法及代碼示例
- GO NewEncoder用法及代碼示例
- GO NumError用法及代碼示例
- GO NotifyContext用法及代碼示例
- GO Node用法及代碼示例
- GO Notify用法及代碼示例
- GO NotFoundHandler用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 NewFromFiles。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。