Home > Backend Development > Golang > Why Can't I Declare a Variable Outside a Function in Go?

Why Can't I Declare a Variable Outside a Function in Go?

Susan Sarandon
Release: 2024-11-29 20:00:15
Original
891 people have browsed it

Why Can't I Declare a Variable Outside a Function in Go?

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)
}
Copy after login

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"
Copy after login
  • Using the var keyword declares a variable named test.
  • The lowercase "t" indicates that the variable is only visible within the package (unexported).
  • The assignment operator = initializes the variable with the value "This is a test".

Variable Characteristics

The test variable:

  • Is accessible from anywhere within the apitest package.
  • Can be reassigned, making it changeable.

Additional Notes

  • Instead of var test = "This is a test", you could write var test string = "This is a test", but it is not considered idiomatic Go.
  • Go also provides the init function for complex package initializations or setting up package state. Init is called before main runs.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template