Home  >  Article  >  Backend Development  >  Why Do I Get 'Non-Declaration Statement Outside Function Body' Error in Go?

Why Do I Get 'Non-Declaration Statement Outside Function Body' Error in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 10:41:02964browse

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.

The above is the detailed content of Why Do I Get 'Non-Declaration Statement Outside Function Body' Error in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn