GO – 文件的包名称

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

GO - Package name of files

问题

我了解到,在一个目录中,所有的.go文件必须命名为相同的包名。


考虑下面来自GitHub的示例:

fogleman/nes/
  nes/	
    apu.go	
    cartridge.go
    console.go	
    controller.go
    cpu.go	
    filter.go	
    ines.go	
    mapper.go	
    mapper1.go	
    mapper2.go	
    mapper3.go	
    mapper4.go	
    mapper7.go	
    memory.go	
    palette.go	
    ppu.go	
  ui/	
  util/
  .gitignore	
  LICENSE.md	
  README.md	
  main.go	

所以,目录../fogleman/nes/nes中的所有.go文件的包名都是nes(与目录名相同)。

同样地,目录../fogleman/nes/ui中的所有.go文件的包名都是ui(与目录名相同)。


考虑下面的两个文件,我有一个问题:

目录../fogleman/nes/util中的roms.go文件的包名是main(与目录名不同)

目录../fogleman/nes中的main.go文件的包名是main(与目录名不同)。

问题:

为什么包名(main)与其目录名不同?

英文:

I learnt that, all .go files in a directory must name the same package.


Considering below example from github,

fogleman/nes/
  nes/	
    apu.go	
    cartridge.go
    console.go	
    controller.go
    cpu.go	
    filter.go	
    ines.go	
    mapper.go	
    mapper1.go	
    mapper2.go	
    mapper3.go	
    mapper4.go	
    mapper7.go	
    memory.go	
    palette.go	
    ppu.go	
  ui/	
  util/
  .gitignore	
  LICENSE.md	
  README.md	
  main.go	

So, All .go files in directory(../fogleman/nes/nes) have the package name nes(same as directory name).

Similarly, all .go files in directory, ../fogleman/nes/ui have the package name ui(same as directory name).


Considering below two files, I have a question,

1)

roms.go file in directory(../fogleman/nes/util) has package name main(different from directory name)

2)

main.go file in directory(../fogleman/nes) has package main(different from directory name).

Question:

Why package name(main) is different from its directory name?

答案1

得分: 2

我相信这个仓库的作者打算将roms.go作为一个独立的程序进行测试。如果不将这个文件放在main包中,就无法实现这一点。如果你在项目的根目录下,可以执行以下命令:

cd util

go run roms.go path/to/roms/dir

英文:

I believe the author of this repo intended on running roms.go as a separate program for testing. Without putting this file in package main, this could not be done. If you are in the root project directory:

cd util

go run roms.go path/to/roms/dir

huangapple
  • 本文由 发表于 2017年1月29日 04:18:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/41914416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定