Go: Get alias of imported package

Viewed 64

I have a snippet like this:

f, err := parser.ParseFile(fset, ".", nil, 0)
if err != nil {
    panic(err)
}
for _, s := range f.Imports {
    fmt.Println(i.Path.Value) //prints import path
}

How can I get the alias of the import? Like if I have:

import (
    test "github.com/username/some-repo"
)

How can I get the alias test?

1 Answers

If s is an *ast.ImportSpec, you get the import alias with:

s.Name.String()

or

s.Name.Name

The struct is defined as:

type ImportSpec struct {
    Doc     *CommentGroup // associated documentation; or nil
    Name    *Ident        // local package name (including "."); or nil
    Path    *BasicLit     // import path
    Comment *CommentGroup // line comments; or nil
    EndPos  token.Pos     // end of spec (overrides Path.Pos if nonzero)
}

So:

    for _, s := range f.Imports {
        fmt.Println(s.Name.String())
    }

Using Ident.String() is better because if doesn't panic if the Ident itself is nil, e.g. in case of import statements with no alias.

Related