Go: Get alias of imported package

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

Go: Get alias of imported package

问题

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

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

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

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

我如何获取别名 test

英文:

I have a snippet like this:

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

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

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

How can I get the alias test?

答案1

得分: 2

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

  1. s.Name.String()

或者

  1. s.Name.Name

该结构体定义如下:

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

因此:

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

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

英文:

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

  1. s.Name.String()

or

  1. s.Name.Name

The struct is defined as:

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

So:

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

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:

确定