Non-Declaration Statement Outside Function Body in Go
In Go, a non-declaration statement outside a function body triggers an error. This is observed in the code snippet:
package apitest import ( "fmt" ) test := "This is a test." func main() { fmt.Println(test) test = "Another value" fmt.Println(test) }
This code attempts to declare a variable outside the main() function and assign a value to it. However, Go does not allow non-declaration statements outside of function bodies.
Idiomatic Approach
The idiomatic Go way to declare a variable accessible from anywhere within a package but not necessarily a constant is:
var test = "This is a test"
Variable Characteristics
The test variable:
Additional Notes
The above is the detailed content of Why Can't I Declare a Variable Outside a Function in Go?. For more information, please follow other related articles on the PHP Chinese website!