正确使用软件包,如何安排目录,文件名,单元测试文件? [英] To use package properly, how to arrange directory, file name, unit test file?

查看:143
本文介绍了正确使用软件包,如何安排目录,文件名,单元测试文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的源文件树是这样的:

  / src 
/ pkg
/ foo
foo.go
foo_test.go

Inside foo.go:

 包foo 

func bar(n int){
...
}

在foo_test.go中:

<$ p $ ($ * b $($)



$ b $ $ b

我的问题是:


  1. 包名是否与目录名,源文件名有关?

  2. 如果只有一个包的源文件,需要将它放在一个目录中?

  3. 我应该将foo.go和foo_test.go放在同一个包中吗?

  4. 在foo_test.go中,它和foo.go在同一个包中,I没有导入foo。但是当我用6g编译foo_test.go时,它说bar()是未定义的。我应该怎么做? >


    共享相同PackageName的一组文件形成一个包的实现。一个实现可能需要一个包的所有源文件位于同一个目录中。

    因此,似乎对命名没有要求的文件/目录,但将所有形成包的文件放在一个目录中会更安全。



    2 - 显然文件必须位于某个目录中。我假设你的意思是我应该把它放在 src 的子目录中吗?在我看来,根据上面的引用,如果你真的想要的话,你可以直接在 src 中包含所有文件。



    3 - 是的。



    4 - 使用 go test


    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 - 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

    这篇关于正确使用软件包,如何安排目录,文件名,单元测试文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆