Understanding Variables in Go

I am a self-taught Fullstack Web and Mobile App developer with over 4 years of experience. I have built a few apps using React and React Native with a backend in Nest.JS and Express.JS
Introduction to Variables
In Go, a variable is a storage location that can hold a value that might change as your program runs. Variables are declared using the var keyword, and the syntax looks like this:
var identifier type
identifier: The name of the variable.
type: The data type of the variable (e.g., int, bool, string).
Unlike many other languages, Go specifies the type after the variable name. Once a variable is declared, Go automatically allocates memory and assigns a default value based on its type. For example:
int: default is 0float: default is 0.0bool: default isfalsestring: default is an empty string ("")For other types, like pointers or structs, the default is typically
nilor a zeroed version of the type.
Here’s an example:
var number int
var decision bool
fmt.Println(number) // Outputs: 0
fmt.Println(decision) // Outputs: false
The number and decision variables are initialized with the default values 0 and false, respectively.
Assigning Values to Variables
To give a variable a value, we use the assignment operator (=). Assignment can happen when the variable is declared or later during the program's execution.
var identifier type = value
For example:
var number int = 5
var decision bool = true
fmt.Println(number) // Outputs: 5
fmt.Println(decision) // Outputs: true
Go also allows automatic type inference, meaning the compiler can figure out the variable's type based on the value you assign:
var number = 5
var decision = true
fmt.Println(number) // Outputs: 5
fmt.Println(decision) // Outputs: true
In this case, you can omit the type declaration and Go will infer number as an int and decision as a bool.
Using the := Assignment Operator
Go offers a shorter way to declare and initialize variables using the := operator. This is a shorthand for declaring a variable and assigning it a value, all in one step:
number := 5
decision := true
This form is preferred because it's more concise, but it can only be used inside functions—not at the package level. It’s important to note that := this creates a new variable. If you try to reassign a variable using := in the same scope, Go will throw an error:
number := 5
number := 20 // Error: no new variables on left side of :=
Instead, to change the value of an existing variable, just use =:
number = 20 // This is fine
Key Points to Remember
If you declare a variable but don’t use it, Go will give you a compile-time error: "variable declared and not used."
If you try to use a variable that hasn't been declared, you’ll get another error: "undefined."
Now that we’ve covered how variables work in Go, including declaration, assignment, and shorthand syntax, it's time to explore how variable scope and references are handled in Go.




