Go: Get alias of imported package

huangapple go评论68阅读模式
英文:

Go: Get alias of imported package

问题

我有一个类似这样的代码片段:

f, err := parser.ParseFile(fset, ".", nil, 0)
if err != nil {
    panic(err)
}
for _, s := range f.Imports {
    fmt.Println(i.Path.Value) // 打印导入路径
}

我如何获取导入的别名?比如我有以下代码:

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

我如何获取别名 test

英文:

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

得分: 2

如果s*ast.ImportSpec,你可以通过以下方式获取导入别名:

s.Name.String()

或者

s.Name.Name

该结构体定义如下:

type ImportSpec struct {
	Doc     *CommentGroup // 相关文档; 或者为nil
	Name    *Ident        // 本地包名(包括“.”); 或者为nil
	Path    *BasicLit     // 导入路径
	Comment *CommentGroup // 行注释; 或者为nil
	EndPos  token.Pos     // 规范的结束位置(如果非零,则覆盖Path.Pos)
}

因此:

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

使用Ident.String()更好,因为如果Ident本身为nil,例如在没有别名的导入语句中,它不会引发恐慌。

英文:

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.

huangapple
  • 本文由 发表于 2022年7月11日 22:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/72940052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定