Standard library / go/ast

go/ast.CommentMap.Update()

Moves comment associations from an old node to a replacement and returns the replacement node. Expected stdout: 'true 1\n'.

Formal Syntax & Structure

go syntaxgo
func (cmap CommentMap) Update(old, new Node) Node

Parameters & Attributes

NameTypeDescription
oldNodePreviously associated AST node.
newNodeReplacement AST node.

Return Value

Node

Moves comment associations from an old node to a replacement and returns the replacement node.

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/ast"  "go/parser"  "go/token")
func check(e error) {  if e != nil {    panic(e)  }}func parsed(src string) (*token.FileSet, *ast.File) {  fs := token.NewFileSet()  f, e := parser.ParseFile(fs, "demo.go", src, parser.ParseComments|parser.SkipObjectResolution)  check(e)  return fs, f}func find[T ast.Node](root ast.Node) T {  for n := range ast.Preorder(root) {    if x, ok := n.(T); ok {      return x    }  }  panic("node not found")}
func main() {  fs, f := parsed("package p\n// doc\nvar A int\n")  m := ast.NewCommentMap(fs, f, f.Comments)  old := f.Decls[0]  replacement := &ast.GenDecl{Tok: token.VAR}  fmt.Println(m.Update(old, replacement) == replacement, len(m[replacement]))}
Go Reference