douping3427 2016-08-12 21:36
浏览 36
已采纳

可以由编译器推断“ package”关键字的目的是什么? [重复]

This question already has an answer here:

All of the Go source files inside directory x have package name x declared on top. I know this is not mandatory but doing otherwise will make things unnecessarily complex. So why the go compiler does not infer the package name from directory name?

This exists in almost many other languages like Java or C# where you are forced to declare what can be easily calculated at compile time.

What is the rationale?

</div>
  • 写回答

1条回答 默认 最新

  • duanhoupeng6642 2016-08-12 21:48
    关注

    Without package you wouldn't be able to distinguish between main programs and libraries.

    Furthermore, according to the language specification, the language does not require a package to be identical with a directory:

    An implementation may require that all source files for a package inhabit the same directory.

    And in practice some packages have different names than their import paths:

    If the PackageName is omitted, it defaults to the identifier specified in the package clause of the imported package.

    Consider github.com/google/go-gcm which has package gcm in its files. Projects that use this library will have:

    import "github.com/google/go-gcm"
    

    And then call things like this:

    res, err := gcm.SendHttp(APIKey, notification)
    

    This is particularly common with - because you can't use it in an identifier.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?