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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题