Variables
In Go, variables are declared using the var keyword, followed by the variable name and type, e.g., var userName string.
As always, there are some types that can be inferred: int, float64, string, bool, and byte (literally 8 bits).
TIP
You can declare multiple variables at once, e.g.,
var userName, userAge stringorvar userName, userAge = "John", 30.
Constants
Just like variables, constants are declared using the const keyword, followed by the constant name and type, e.g., const pi float64 = 3.14.
Constants must be known at compile time and cannot be changed during runtime.
// this will not compile because the value is not known at compile time
const currentTime := time.Now()Walrus Operator
Go has a shorthand for declaring and initializing variables using the := operator, known as the walrus operator. For example: userAge := 30 declares and initializes an integer variable userAge with the value 30. It infers the type based on the assigned value.
When a variable is declared but not initialized, it gets a default value: 0 for numeric types, false for booleans, and "" (empty string) for strings.
TIP
The walrus operator can only be used inside functions, but it should be used whenever possible for brevity.