Home  >  Article  >  Backend Development  >  How do I access global variables in Go?

How do I access global variables in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 20:12:02824browse

How do I access global variables in Go?

Accessing Global Variables in Go

You are attempting to declare a globally accessible variable outside of the main() function in Go, but are encountering an error. The appropriate approach depends on whether the variable should be constant or mutable.

For Non-Constant Variables

To declare a non-constant variable outside of a function and make it accessible within a package, use the following syntax:

var test = "A Test Value"

In this case, the lowercase t in the variable name indicates that it is only visible within the package (unexported).

Here's an example:

package apitest

import "fmt"

var sessionID string

func main() {
    // Check and update sessionID as needed...
}

For Constant Variables

For constants, use the const keyword instead of var. The syntax is:

const test = "A Test Value"

Constants must be given a value during declaration and cannot be changed later.

Additional Notes

  • You can use init() function to initialize package-level variables before main() is run.

The above is the detailed content of How do I access global variables in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn