Variables

Variable Definitions

Unlike other static languages, we define varialbes like this

1
2
3
4
func variable(){
var a int
var s string
}

Now compare C,

1
2
int a;
char s;

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
2
3
4
5
func varInitVar(){
var a int
var s string
fmt.Printf("%d %q\n", a, s)
}

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
2
3
4
5
func varInitValue(){
var a, b int = 3, 4
var s string = "abc"
fmt.Println(a, b, s)
}

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
2
3
4
5
6
func varShorter(){
a, b, c, s := 3, 4, true, "def"
// to reassign a value to e.g. b, we can't use :=
b = 5
fmt.Printlne(a, b, c, s)
}

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
2
3
4
5
6
7
8
package main
import "fmt"

var aa, ss = 3, "kkk"

func main(){
fmt.Println(aa, ss)
}

We can also group those varialbe definition as below

1
2
3
4
5
6
7
8
9
10
11
12
package main
import "fmt"

var (
aa = 3
ss = "kkk"
bb = true
)

func main(){
fmt.Println(aa, ss, bb)
}

Of course the var block can be defined as such

1
2
3
var (
aa, ss, bb = 3, "kkk", true
)