Non-Declaration Statement Outside Function Body in Go
In Go, declaring a variable outside of a function body typically leads to the "non-declaration statement outside function body" error. This occurs because Go strictly enforces scoping rules, requiring variables to be declared within the appropriate block (e.g., inside a function).
Idiomatic Global Variable Declaration
To create a globally accessible variable that is changeable but not a constant, the syntax is:
var test = "This is a test"
Nach dem Login kopieren
- The var keyword is used for variable declaration.
- The name of the variable (test in this case) should start with a lowercase letter to indicate its visibility within the package (unexported).
- The = sign assigns a value to the variable.
Example:
package apitest
import (
"fmt"
)
var test = "This is a test" // Globally accessible variable
func main() {
fmt.Println(test)
test = "Another value"
fmt.Println(test)
}
Nach dem Login kopieren
Extended Explanation
-
Variable Initialization in Functions: Inside functions, you can declare a variable and assign it a value later using the := operator. However, := is not valid for global variable declarations.
-
Type Inference: Go supports type inference, where the compiler can determine the type of a variable based on its initial value.
-
Changing Package-Level Variables: Package-level variables, including globally accessible variables, can be changed from within functions using the same variable name (e.g., changeTest(newVal) in the provided code snippet).
-
Init Function: For complex package initialization, Go provides the init function, which is automatically executed before main(). It can be used to set up initial states for the package.
Das obige ist der detaillierte Inhalt vonWarum erhalte ich in Go die Fehlermeldung „Non-Declaration Statement Outside Function Body'?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!