Does it make sense to have two packages in the same directory?

前端 未结 4 548
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 09:43

I have a project that provides a library (exports some funcs) and also must provide a command-line interface (there must be an executable file).

Example of directory

4条回答
  •  不知归路
    2020-12-16 10:02

    In most cases, no. However, there is an exception for unit tests.

    Working Example:

    Here are 2 different packages (mypackage and mypackage_test) in 1 directory (mypackage). The compiler will not complain about this.

    mypackage folder:

    mypackage/
      foo.go
      foo_test.go
    

    mypackage/foo.go:

    package mypackage
    
    func Add(a int, b int) int {
        return a + b
    }
    

    mypackage/foo_test.go:

    package mypackage_test
    
    // Unit tests...
    

    Rules:

    1. The 2 packages must have the following names:

      • NameOfDirectory.
      • NameOfDirectory + _test.
    2. The names of the files in the _test package must end with _test.go

    If you're receiving a confusing compiler error along the lines of found packages "foo" and "bar", you've probably broken one or more of these rules.

提交回复
热议问题