为了正确使用包,如何安排目录、文件名和单元测试文件?

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

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)
    ...
}

我的问题是:

  1. 包名与目录名、源文件名有关吗?
  2. 如果一个包只有一个源文件,我需要将它放在一个目录中吗?
  3. 我应该将 foo.gofoo_test.go 放在同一个包中吗?
  4. 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:

  1. Does package name relates to directory name, source file name?
  2. If there is only one source file for a package, need I put it in a directory?
  3. Should I put foo.go and foo_test.go in the same package?
  4. In the foo_test.go, as it's in the same package as foo.go, I didn't import foo. But when I compile foo_test.go with 6g, it says bar() 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

huangapple
  • 本文由 发表于 2010年2月2日 15:32:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/2182469.html
匿名

发表评论

匿名网友

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

确定