duandun3178 2017-08-19 23:08
浏览 78
已采纳

如何在多个源文件中解析导入语句?

I've been trying to find an answer to this question without success.

The question is about import statements in Go when a package consists of multiple source files.

Let's say I have a package called math which consists of multiple files:

|-- math
   |-- add.go
   |-- subtract.go
   |-- divide.go
   |-- multiply.go

Let's assume that the math package makes use of the fmt package therefore it needs the appropriate import statement. But since we have four separate files, we have to import the fmt package multiple times (at least to my understanding):

// add.go
import "fmt"

// subtract.go
import "fmt"

// divide.go
import "fmt"

// multiply.go
import "fmt"

Now the question is, what happens when the package is compiled? Are the statements simply merged together?

If so, why do we have to import the package multiple times (once per each file) and not just have a single file with all the import statements so as to not repeat ourselves?

  • 写回答

1条回答 默认 最新

  • doubiantiao4994 2017-08-20 02:36
    关注

    The specification says:

    The scope of the package name of an imported package is the file block of the file containing the import declaration.

    Because imports do not have package scope, imports are not merged together and are required in each file that uses the import.

    The scoping for imports is unrelated to how the compiler and linker load imported packages. These tools are smart enough to load any given package once.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看