Unlike other static languages, we define varialbes like this
Now compare C,
In GO, we put variable name before data type. This is actually more natural as we usually think about the variable name before considering its data type.
Unlike C or Java, after defining varialbes, Go will assign some initial values to those variables, e.g. 0 for int variables and
"" (empty string) for string variables.
Here we use
Printf to format print their initial values. The output would be
There are several ways to assign initial values in Go. Note, once a variable is defined, it must be used.
Go is smart enough to infer the data type, aka type deduction, so
var a, b int = 3, 4 can be shortened as
var a, b = 3, 4.
We can even put different types in one line
var a, b, s, check = 3, 4, "abc", false
There’s another even shorter variable assignment in Go, which is similar to the walrus operator in Python.
It’s used for the initial value assignment and can only be used once.
In the examples above, I defined variables within the function scope. They can be defined in “package” scope as well.
However, in the “package” scope we can’t use
:=. The package scope is similar to the global scope in other languages.
We can also group those varialbe definition as below
Of course the
var block can be defined as such