首頁  >  文章  >  後端開發  >  為什麼在 Go 中會出現「函數體以外的非宣告語句」錯誤?

為什麼在 Go 中會出現「函數體以外的非宣告語句」錯誤?

Patricia Arquette
Patricia Arquette原創
2024-11-13 10:41:02924瀏覽

Why Do I Get

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.

以上是為什麼在 Go 中會出現「函數體以外的非宣告語句」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn