-3

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?

Cirelli94
  • 1,714
  • 1
  • 15
  • 24
  • 4
    It's in the [Language Specification](https://go.dev/ref/spec). – icza Dec 22 '21 at 15:48
  • 3
    https://go.dev/ref/spec#Declarations_and_scope – eglease Dec 22 '21 at 15:49
  • 2
    Does this answer your question? [Understanding variable scope in Go](https://stackoverflow.com/questions/52503560/understanding-variable-scope-in-go) – eglease Dec 22 '21 at 15:49
  • 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? – Cirelli94 Dec 22 '21 at 15:51
  • 3
    `_test.go` files are ignored by the go tool unless you're running tests. – icza Dec 22 '21 at 15:52

1 Answers1

4

Declarations and scope are detailed in different parts of the Language Specification, for details and comprehensive overview, see Understanding variable scope in Go.

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.

icza
  • 389,944
  • 63
  • 907
  • 827