// Create a CommentGroup with two comments. cg := &ast.CommentGroup{ List: []*ast.Comment{ {Text: "// This is a comment."}, {Text: "// This is another comment."}, }, } // Print the comments in the CommentGroup. for _, c := range cg.List { fmt.Println(c.Text) }
// Find all CommentGroups in a Go source file. fset := token.NewFileSet() node, err := parser.ParseFile(fset, "example.go", nil, parser.ParseComments) if err != nil { log.Fatal(err) } // Traverse the AST to find CommentGroups. ast.Inspect(node, func(n ast.Node) bool { switch x := n.(type) { case *ast.CommentGroup: fmt.Println(x.Text()) } return true })This code uses the parser.ParseFile function to parse a Go source file and generate an AST. It then uses the ast.Inspect function to traverse the AST and find all CommentGroups in the file. The Text() method is used to print the contents of each CommentGroup.