GO语言"go/ast"包中"CommentMap"类型的用法及代码示例。
CommentMap 将 AST 节点映射到与其关联的评论组列表。有关关联的说明,请参见NewCommentMap。
用法:
type CommentMap map[Node][]*CommentGroup
例子:
此示例说明如何在 Go 程序中删除变量声明,同时使用 ast CommentMap 保持正确的注释关联
package main
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
)
func main() {
// src is the input for which we create the AST that we
// are going to manipulate.
src := `
// This is the package comment.
package main
// This comment is associated with the hello constant.
const hello = "Hello, World!" // line comment 1
// This comment is associated with the foo variable.
var foo = hello // line comment 2
// This comment is associated with the main function.
func main() {
fmt.Println(hello) // line comment 3
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
if err != nil {
panic(err)
}
// Create an ast.CommentMap from the ast.File's comments.
// This helps keeping the association between comments
// and AST nodes.
cmap := ast.NewCommentMap(fset, f, f.Comments)
// Remove the first variable declaration from the list of declarations.
for i, decl := range f.Decls {
if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
copy(f.Decls[i:], f.Decls[i+1:])
f.Decls = f.Decls[:len(f.Decls)-1]
break
}
}
// Use the comment map to filter comments that don't belong anymore
// (the comments associated with the variable declaration), and create
// the new comments list.
f.Comments = cmap.Filter(f).Comments()
// Print the modified AST.
var buf bytes.Buffer
if err := format.Node(&buf, fset, f); err != nil {
panic(err)
}
fmt.Printf("%s", buf.Bytes())
}
输出:
// This is the package comment. package main // This comment is associated with the hello constant. const hello = "Hello, World!" // line comment 1 // This comment is associated with the main function. func main() { fmt.Println(hello) // line comment 3 }
相关用法
- GO Command用法及代码示例
- GO CommandContext用法及代码示例
- GO Compare用法及代码示例
- GO CopyN用法及代码示例
- GO CopyBuffer用法及代码示例
- GO ContainsRune用法及代码示例
- GO Copysign用法及代码示例
- GO Cosh用法及代码示例
- GO Config用法及代码示例
- GO Count用法及代码示例
- GO ContainsAny用法及代码示例
- GO Cos用法及代码示例
- GO Conn.ExecContext用法及代码示例
- GO Copy用法及代码示例
- GO Contains用法及代码示例
- GO Chmod用法及代码示例
- GO Cmd.Start用法及代码示例
- GO CanBackquote用法及代码示例
- GO CreateTemp用法及代码示例
- GO Cut用法及代码示例
注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 CommentMap。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。