Standard library / go/ast
go/ast.SortImports()
Sorts consecutive runs of imports and removes duplicate imports when safe. Use the file set associated with the parsed source. Inspect the import declaration Specs, not File.Imports, which may retain its original order. Expected stdout: '"fmt"\n"strings"\n'.
Formal Syntax & Structure
go syntaxgo
func SortImports(fset *token.FileSet, f *File)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fset | *token.FileSet | Non-nil file set that records source positions. |
| f | *File | Predicate or callback controlling traversal, filtering or printing, as described above. |
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\nimport (\n\"strings\"\n\"fmt\"\n)") ast.SortImports(fs, f) for _, s := range f.Decls[0].(*ast.GenDecl).Specs { fmt.Println(s.(*ast.ImportSpec).Path.Value) }}