我的目录结构是这样的:
Animal/
dog/
chiwawa.go
rabbit.go
chiwawa.go
和 rabbit.go
都在文件顶部打包名为:“package animal”。但是,当我尝试在 rabbit.go
中使用 chiwawa.go
中的变量 var Food = apple
时,出现错误 - undefined : 食物
。
当我将 chiwawa.go
直接放在 Animal
下而没有 dog
目录时,我没有任何问题。
这在 Go 中是故意的吗?我可以在保留包名称和目录结构的同时解决这个问题吗?
最佳答案
The go tool is designed to work with open source code maintained in public repositories. Although you don't need to publish your code, the model for how the environment is set up works the same whether you do or not.
Go code must be kept inside a workspace. A workspace is a directory hierarchy with three directories at its root:
- src contains Go source files organized into packages (one package per directory),
- pkg contains package objects, and
- bin contains executable commands.
The go tool builds source packages and installs the resulting binaries to the pkg and bin directories.
The src subdirectory typically contains multiple version control repositories (such as for Git or Mercurial) that track the development of one or more source packages.
To give you an idea of how a workspace looks in practice, here's an example:
bin/ hello # command executable outyet # command executable pkg/ linux_amd64/ github.com/golang/example/ stringutil.a # package object src/ github.com/golang/example/ .git/ # Git repository metadata hello/ hello.go # command source outyet/ main.go # command source main_test.go # test source stringutil/ reverse.go # package source reverse_test.go # test source
This workspace contains one repository (example) comprising two commands (hello and outyet) and one library (stringutil).
A typical workspace would contain many source repositories containing many packages and commands. Most Go programmers keep all their Go source code and dependencies in a single workspace.
对于 Go 工具,一个 Go 包的所有 Go 源文件应该在同一个目录中。
关于go - 包命名 : error exporting variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29584650/