英文:
Where is explained the scope of variables in Go in official documentation?
问题
我在go.dev上找不到关于私有/全局变量和变量作用域的解释。
作为一个相关的问题,我在尝试从_test.go
文件中导入一个变量时遇到了困难。当然,这在文档中没有提到,但我认为这与编译器有关。
英文:
I can't find any place in go.dev where private/global variables and the scope of variables are explained.
As a related problem, I was struggling trying to import a variable from a _test.go
file. Of course this is not in that documentation, but I think is related to the compiler?
答案1
得分: 4
声明和作用域的详细信息在语言规范的不同部分中进行了详细说明,有关详细信息和全面概述,请参阅https://stackoverflow.com/questions/52503560/understanding-variable-scope-in-go/52506086#52506086。
正如您在评论中提到的,您的问题是无法从_test.go
文件中导入变量。语言规范中没有提到这一点,所以这是一种实现限制。
引用命令文档:编译包和依赖项:
在编译包时,构建会忽略以“_test.go”结尾的文件。
它们仅在运行测试时使用。测试包:
“Go test”会重新编译每个包以及与文件模式“*test.go”匹配的任何文件。这些附加文件可以包含测试函数、基准函数和示例函数。有关更多信息,请参阅“go help testfunc”。每个列出的包都会导致执行单独的测试二进制文件。以“”(包括“_test.go”)或“.”开头的文件将被忽略。
声明带有后缀“_test”的测试文件将被编译为单独的包,然后与主测试二进制文件链接和运行。
英文:
Declarations and scope are detailed in different parts of the Language Specification, for details and comprehensive overview, see https://stackoverflow.com/questions/52503560/understanding-variable-scope-in-go/52506086#52506086.
As you mentioned in the comments, your problem is that you can't import variables from _test.go
files. The language spec doesn't mention this, so this is an implementation restriction.
Quoting from Command documentation: Compile packages and dependencies:
> When compiling packages, build ignores files that end in '_test.go'.
They are only used when you run tests. Test packages:
> 'Go test' recompiles each package along with any files with names matching the file pattern "*_test.go". These additional files can contain test functions, benchmark functions, and example functions. See 'go help testfunc' for more. Each listed package causes the execution of a separate test binary. Files whose names begin with "_" (including "_test.go") or "." are ignored.
>
> Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论