In Go, like any other language variables are containers that store data. These containers can be references across your code.
var age int = 25
name := "Gopher"
Here, we’ve declared two variables: ‘age’ as an integer and ‘name’ as a string. Notice the two different ways of declaring variables in Go.
In Go, there are two primary ways to declare variables:
1. Using the 'var' keyword
This is the traditional way of declaring variables. You use the ‘var’ keyword followed by the variable name and type.
var age int = 25
var name string = "Gopher"
You can also declare variables without initializing them:
var age int
var name string
2. Using short variable declaration (:=)
This is a shorthand notation that allows you to declare and initialize variables in one line. Go will infer the type based on the value.
age := 25
name := "Gopher"
This method can only be used inside functions. It’s concise and commonly used when you know the initial value of the variable.
Both methods are valid in Go, and the choice often depends on the context and personal preference. The ‘var’ keyword is typically used for package-level variables, while the short declaration is common inside functions.
How to Declare variables in GO, checkout this video Explanation
Stay tuned for more Go adventures and happy coding!