Go language: Using package name inside package scope (for Examples)

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

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
}

现在,这给我带来了两个好处:

  1. 当我运行go test时,这个示例会被执行。
  2. 它会出现在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:

  1. This example is executed when I am running go test and
  2. 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包中。你可以在同一个目录下同时拥有hellohello_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.

huangapple
  • 本文由 发表于 2014年10月9日 06:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/26267359.html
匿名

发表评论

匿名网友

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

确定