Golang go/ast.GenDecl type examples
package go/ast
A GenDecl node (generic declaration node) represents an import, constant, type or variable declaration. A valid Lparen position (Lparen.Line > 0) indicates a parenthesized declaration.
Golang go/ast.GenDecl type usage examples
Example 1:
func getExportedDeclarationsForFile(path string) ([]string, error) {
fset := token.NewFileSet()
tree, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
return []string{}, err
}
declarations := []string{}
ast.FileExports(tree)
for _, decl := range tree.Decls {
switch x := decl.(type) {
case *ast.GenDecl:
switch s := x.Specs[0].(type) {
case *ast.ValueSpec:
declarations = append(declarations, s.Names[0].Name)
}
case *ast.FuncDecl:
declarations = append(declarations, x.Name.Name)
}
}
return declarations, nil
}
Example 2:
func importsForRootNode(rootNode *ast.File) (imports *ast.GenDecl, err error) {
for _, declaration := range rootNode.Decls {
decl, ok := declaration.(*ast.GenDecl)
if !ok || len(decl.Specs) == 0 {
continue
}
_, ok = decl.Specs[0].(*ast.ImportSpec)
if ok {
imports = decl
return
}
}
err = errors.New(fmt.Sprintf("Could not find imports for root node:\n\t%#v\n", rootNode))
return
}
References :
https://github.com/onsi/ginkgo/blob/master/ginkgo/nodot/nodot.go
https://github.com/onsi/ginkgo/blob/master/ginkgo/convert/import.go
Advertisement
Something interesting
Tutorials
+8.2k Golang : Qt splash screen with delay example
+12.8k Golang : Convert int(year) to time.Time type
+8.1k Golang : How To Use Panic and Recover
+12.7k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+18k Golang : Get all upper case or lower case characters from string example
+8.9k Golang : Gaussian blur on image and camera video feed examples
+20.2k Golang : Compare floating-point numbers
+30.9k Golang : Interpolating or substituting variables in string examples
+5.4k Gogland : Datasource explorer
+28.5k Golang : Change a file last modified date and time
+4.7k Linux/MacOSX : How to symlink a file?
+18.2k Golang : Get path name to current directory or folder