All About Variables & Constants

Chapter 4

Variables#

Declaring variables can be done using the var keyword or using the short declaration symbol :=.

var i int // default value is 0
i := 10 // implicit type declaration, i is of type int
j := i // j is also an int

var statements can be at both package or function levels.

Short declarations with := is only available at the function level. := uses implicit type declaration, i.e. it infers the type of the variable from the declaration. This is known as type inference.

Initialising Variables#

We can initialise multiple variables on the same line.

var i, j, k int = 1, 2, 3

Basic Types in Go#

bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
// represents a Unicode code point
float32 float64
complex64 complex128

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
https://tour.golang.org/basics/11

Zero Values#

When we declare a variable without an initial value, it takes on a default zero value.

Zero value for types:

  • int takes 0
  • boolean takes false
  • string takes ""

Type Conversions#

In Go, we need to explicitly convert between types. Implicitly converting int to float or vice versa is not allowed.

var x int = 1
var y float64 = float64(x)

Exported Names#

To make a variable or as we will see later for methods, we name it starting with a capital letter, e.g. Ball. Variables starting with a lowercase alphabet is not exported, and hence, will be not be accessible outside the package, e.g. oranges.

Named Return Values#

func namedReturn(num int) (a, b int) {
a = num / 2
b = num / 3
return a, b
}
func main() {
i, j := namedReturn(6)
fmt.Println(i, j) // prints 3, 2
}

We can also omit the a, b in the return statement of namedReturn function. This is known as a naked return. However, this is only recommended for short functions so as to maintain code readbility.

Exercise: Swap 2 Variables

i := 100
j := 5
fmt.Println(i ,j) // prints 100, 5
i, j = j, i
fmt.Println(i ,j) // prints 5, 100

In Go, we can swap the values stored in two variables in just one line as shown above (similar to Python).

Constants#

Constants can be declared with the const keyword.

const x = 100

Note: := is only used for variables. You cannot use it for constants.