Variables
Variable Definitions
Unlike other static languages, we define varialbes like this
1 | func variable(){ |
Now compare C,
1 | int a; |
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.
Initial Values
Default Initial Values
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.
1 | func varInitVar(){ |
Here we use Printf
to format print their initial values. The output would be
1 | 0 "" |
Assign Initial Values
There are several ways to assign initial values in Go. Note, once a variable is defined, it must be used.
1 | func varInitValue(){ |
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.
1 | func varShorter(){ |
Scope
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.
1 | package main |
We can also group those varialbe definition as below
1 | package main |
Of course the var
block can be defined as such
1 | var ( |