Variables are fundamental components in Go programming. They serve as containers for storing and manipulating data throughout your code. Understanding how to declare, initialize, and use variables is crucial for effective Go development.
Go offers multiple ways to declare variables. The most common method uses the var
keyword:
var name string
var age int
var isStudent bool
You can also declare multiple variables in a single line:
var x, y, z int
Variables can be initialized at the time of declaration:
var name string = "John Doe"
var age int = 30
var isStudent bool = true
Go's type inference allows you to omit the type when initializing:
var name = "John Doe"
var age = 30
var isStudent = true
For concise code, use the short variable declaration operator :=
inside functions:
func main() {
name := "John Doe"
age := 30
isStudent := true
}
Uninitialized variables in Go are assigned zero values:
Variables declared outside any function have package scope. They're accessible throughout the package. Variables declared within a function have local scope, limited to that function.
For values that won't change, use constants:
const Pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)
Learn more about constants in Go in our Go Constants guide.
:=
) inside functions for brevity.To deepen your understanding of Go variables, explore these related topics:
Mastering variables is essential for writing efficient and maintainable Go code. Practice declaring and using variables in different contexts to solidify your understanding.