Standard library / go/printer

go/printer.CommentedNode

Bundles a supported syntax node and its comment groups for printing. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
type CommentedNode struct {  Node     any  Comments []*ast.CommentGroup}

Working Example

Example Snippetgo
package main
import (  "bytes"  "fmt"  "go/parser"  "go/printer"  "go/token"  "strings")
func check(e error) {  if e != nil {    panic(e)  }}
func main() {  fs := token.NewFileSet()  f, err := parser.ParseFile(fs, "demo.go", "package p\n// retained\nvar X=1\n", parser.ParseComments)  check(err)  n := printer.CommentedNode{Node: f, Comments: f.Comments}  var b bytes.Buffer  check(printer.Fprint(&b, fs, &n))  fmt.Println(strings.Contains(b.String(), "// retained"))}
Go Reference