Home > Article > Backend Development > Why Can't I Assign a Value to a Variable Outside of a Function in Go?
Non-Declaration Statement Outside Function Body in Go
In Go, it's not possible to declare variables outside of functions using a non-declaration statement. This error occurs when trying to assign a value to a non-declared variable, as seen in the following example:
Solution
To declare a globally-accessible variable in Go, use the var keyword outside of the main function. The variable's name should start with a lowercase letter to make it package-private (only accessible within its package).
This method allows you to declare a variable outside of a function and change its value within functions in the same package.
Additional Information
Sample Code
Here's an example of how to use a package-private variable and change its value:
In this example, the sessionID variable is accessible from anywhere within the apitest package. It's initialized to an empty string in the main function and updated within the updateSessionID function.
The above is the detailed content of Why Can't I Assign a Value to a Variable Outside of a Function in Go?. For more information, please follow other related articles on the PHP Chinese website!