Golang Basics - Variables

Variables in Go, just like in other languages, are used to store and represent data. Every variable in Go has a type and a value.

Declaration

Lets look at the declaration of an integer type:

var i int = 5

This declares a variable named i of type int with a value of 5. The Go compiler is pretty smart, so you can sometimes omit some of the declarations. For example:

var i = 5

The compiler infers that 5 is of type int, and so assigns that type to i. We can also declare the type without declaring the value:

var i int

Now the value of i is initialized to the default integer value, which is 0. Another useful shorthand is the := operator, which initializes a variable and infers its type as well:

i := 5
// This is equivalent to
// var i int = 5

Go does not allow you to declare a variable multiple times:

var i int
i := 5

The above code will fail, because the := operator attempts to initalize i once again, after it has already been initialized in the first line.

We can use the = operator to assign a value to variable that's already initialized. This can be done multiple times:

// This is valid code
var i int
i = 5
i = 0
i = 4

It's important to note the difference between the := and the = operators. The := operator is the combined declaration of a variable as well as an assignment of a value. The = operator on the other hand only assigns a value to an existing variable.

Multiple variable assignment

We can assign values, and even declare multiple variables at the same time:

a, b := 1, 2
// We have declared and initialized the variables `a` and `b` with the values of 1 and 2 respectively

// We can even use this to assign values later
var c int
var d int
c, d = 5, 3

Public vs private variables

Go has a rather special way to differentiate between public and private variables: it uses the casing of the first letter of a variable. A variable which starts with an uppercase letter is considered public, and can be accessed by other packages. If the variable begins with a lowercase letter, then it is considered private, and can only be accessed within the package in which it is declared.

package lorem

// These are all private variables, and connot be accessed outside of package lorem
var i int
count := 5

// These are public variables
var Name string
Age := 24
package ipsum

import "lorem"

// These would cause the compiler to throw an error
fmt.Println(lorem.i)
fmt.Println(lorem.count)

// These are valid statements
fmt.Println(lorem.Name)
fmt.Println(lorem.Age)

📖 Read next: Types


Liked this article? Share it on: