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"
- 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)
}
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.
Atas ialah kandungan terperinci Mengapa Saya Mendapat Ralat "Pernyataan Bukan Pengisytiharan Di Luar Badan Fungsi" dalam Go?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!
Kenyataan:Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn