英文:
To use package properly, how to arrange directory, file name, unit test file?
问题
我的源文件树结构如下:
/src
/pkg
/foo
foo.go
foo_test.go
在 foo.go
中:
package foo
func bar(n int) {
...
}
在 foo_test.go
中:
package foo
func testBar(t *testing.T) {
bar(10)
...
}
我的问题是:
- 包名与目录名、源文件名有关吗?
- 如果一个包只有一个源文件,我需要将它放在一个目录中吗?
- 我应该将
foo.go
和foo_test.go
放在同一个包中吗? - 在
foo_test.go
中,由于它与foo.go
在同一个包中,我没有导入foo
。但是当我使用 6g 编译foo_test.go
时,它显示bar() 未定义
。我该怎么办?
英文:
My source files tree is like this:
/src
/pkg
/foo
foo.go
foo_test.go
Inside foo.go
:
package foo
func bar(n int) {
...
}
inside foo_test.go
:
package foo
func testBar(t *testing.T) {
bar(10)
...
}
My questions are:
- Does package name relates to directory name, source file name?
- If there is only one source file for a package, need I put it in a directory?
- Should I put
foo.go
andfoo_test.go
in the same package? - In the
foo_test.go
, as it's in the same package asfoo.go
, I didn't importfoo
. But when I compilefoo_test.go
with 6g, it saysbar() is undefined
. What should I do?
答案1
得分: 9
1 - 语言规范中提到:
> 具有相同PackageName的一组文件形成了一个包的实现。实现可能要求一个包的所有源文件都位于同一个目录中。
因此,似乎对文件/目录的命名没有要求,但如果将形成一个包的所有文件放在一个目录中会更安全。
2 - 显然,文件必须位于某个目录中。我猜你的意思是“我应该将它放在src
的子目录中吗?”根据上面的引用,如果你真的想要,你可以直接将所有文件放在src
中。
3 - 是的。
4 - 使用go test
英文:
1 - The language spec says the following:
> A set of files sharing the same PackageName form the implementation of a package. An implementation may require that all source files for a package inhabit the same directory.
So it seems that there is no requirement on the naming of files / directories, but it would be safer to put all file that form a package in one directory.
2 - Obviously the file must be in some directory. I assume you mean "should I put it in a subdirectory of src
?" It seems to me based on the above quote that you could have all your files in src
directly if you really wanted to.
3 - Yes.
4 - Use go test
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论