Standard library / go/ast

go/ast.FilterDecl()

Removes names and associated declarations that fail the predicate, mutating the declaration in place. Expected stdout: 'true\nPublic\n'.

Formal Syntax & Structure

go syntaxgo
func FilterDecl(decl Decl, f Filter) bool

Parameters & Attributes

NameTypeDescription
declDeclDeclaration to filter in place.
fFilterPredicate or callback controlling traversal, filtering or printing, as described above.

Return Value

bool

Removes names and associated declarations that fail the predicate, mutating the declaration in place.

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() {  _, f := parsed("package p; var Public, private int")  fmt.Println(ast.FilterDecl(f.Decls[0], ast.IsExported))  fmt.Println(find[*ast.ValueSpec](f).Names[0].Name)}
Go Reference