dongshi2836 2017-06-10 17:55
浏览 33
已采纳

如果我在同一个Go包中的2个文件的顶部导入“ fmt”,它会编译两次吗?

I'm using go 1.6 (I need to update). Let's say I have 2 files in a package, and I'm using the fmt package in both of them. You have to explicitly import fmt in both of those files, or the compiler throws and error, so does that mean it stores the fmt binary in my executable twice?

  • 写回答

1条回答 默认 最新

  • douzhu3654 2017-06-10 18:30
    关注

    No, that would be a really poor design (read exception at the end). By the way, it is very easy to check this, create a package named a, consisting of 2 files: aa.go and ab.go. Have both import fmt. Produce the executable (e.g. go build, must called on the main package) and check its size. Now move all code from ab.go that uses the fmt package to aa.go, and remove the fmt import from ab.go. Produce the executable again. They will have the same size.

    Packages are identified by their full path. No matter how many files (of the same package) or how many (different) packages refer to a package, the package will only be included once in the final executable binary.

    Also note that not everything will be included from used packages in the executable binary. Certain things that are not used / referred to may be excluded. For details see Splitting client/server code; and How to remove unused code at compile time?

    There is one exception though, which is the plugins introduced in Go 1.8. Packages referred to by plugins will be included in the compiled plugin –they have to be–, because the plugin has no guarantee what packages will be available in the executable binary that will load it. So if the fmt package is referred to by package main, and also by a plugin, the code of the fmt package will be included in both (in the executable binary and in the compiled plugin). It should be noted that even though the fmt package's code will be present twice (once in the executable and once in the plugin), there will still be only one "instance" of the package in the runtime (in memory) (e.g. its global variables will have one instance, and it will only be initialized once).

    An "edge" case is vendored packages. If a package is vendored in a vendor folder, and a package refers to this vendored package, that is considered distinct from the original (that is vendored), and if the original is also referred to by another package, both will be included in the executable binary (but they are not considered the same, the full path of the vendored is different from the full path of the original).

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c