英文:
Go language: Using package name inside package scope (for Examples)
问题
我目前正在编写我的Go测试脚本中的ExampleFuncs
。例如:
package hello
import "testing"
func ExampleGetSymbol() {
data := GetSymbol("AAPL")
fmt.Println(len(data.Data))
// Output: 21
}
现在,这给我带来了两个好处:
- 当我运行
go test
时,这个示例会被执行。 - 它会出现在godoc文档的
func GetSymbol
下面。
有一件事困扰着我,我想知道是否有什么我应该做的。
对于试图从这个示例中学习的用户来说,这一行:
data := GetSymbol("AAPL")
实际上应该是:
data := hello.GetSymbol("AAPL")
但由于测试与包在同一作用域中,我不能像这样使用它。
所以我想问的问题是:
在包的作用域内是否有一种允许package.field
表示法的方法?
提前感谢您的回答。
英文:
I am currently writing ExampleFuncs
in my Go test scripts. For example:
package hello
import "testing"
func ExampleGetSymbol() {
data := GetSymbol("AAPL")
fmt.Println(len(data.Data))
// Output: 21
}
Now, this gives me two benefits:
- This example is executed when I am running
go test
and - It appears in the godoc documentation under
func GetSymbol
One thing bothers me and I am wondering if there is anything I should do about it.
For the user that's trying to learn from this example, the line
data := GetSymbol("AAPL")
should actually be
data := hello.GetSymbol("AAPL")
but since the test is in the same scope as the package, I cannot use it like this.
So I guess the distilled version of my question would be:
Is there a way to allow package.field
notation inside the package scope?
Thanks in advance
答案1
得分: 3
不要将此代码放在hello
包中,而是放在hello_test
包中。你可以在同一个目录下同时拥有hello
和hello_test
包,并且这样做允许(要求)你按照你建议的方式创建示例。
顺便提一下,这也会导致你只能将测试用例编写到公共API中(至少对于这个文件来说)。这通常是一件好事。但是如果你需要编写私有函数的测试用例,你可以将测试用例分成不同的文件,一些在hello
包中,一些在hello_test
包中。
顺便说一下,关于这个问题的文档有点难找。你可以在go cmd文档的"Test packages"部分找到它。
英文:
Rather than putting this in package hello
, put it in package hello_test
. You're allowed to have both hello
and hello_test
packages in the same directory, and it allows (requires) you to create your examples the way you're suggesting.
Incidentally, this also causes you to write your test cases (at least for this file) only to the public API. This is often a good thing. But if you need to write to private functions, you can split your tests into separate files, some in the hello
package and some in hello_test
.
BTW, documentation for this is slightly buried. You can find it in the "Test packages" section of the go cmd documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论