14

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?
Nik
  • 2,427
  • 2
  • 22
  • 24
Stephen Hsu
  • 4,897
  • 7
  • 28
  • 39

1 Answers1

9

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

jdi
  • 87,105
  • 19
  • 159
  • 196
liwp
  • 6,556
  • 25
  • 38