Variables & Constants

There are multiple ways to declare and initialize variables in Go, one of them is the varkeyword initialization:

var investmentAmount = 1000 // var keyword initialization

In this example, Go looks at the value, sees that it has no floating point numbers and automatically assigns the integer type to this variable. If you had to make a calculation later with a variable which has a decimal place number as value, you would have to convert it to a float64 type.

To fix this issue, we can add a type assignment after the variable name:

var investmentAmount float64 = 1000

Constants

We can also initialize constants. But constants will always have the same value, it can't be changed or re-assigned like the values of variables:

const inflationRate = 2.5 // value will be 2.5 forever

Alternative Variable Declaration Styles

There is a shortcut offered by Go to initialize your Variables that should be used as often as possible, where the type should be inferred by Go. Later on, you’re not able to add a type assignment:

returnRate := 5.5

Initialize multiple variables at once (type assignment)

When we do the type assignment, all the variables must have the same type!

var investmentAmount, years float64 = 1000, 10

Initialize multiple variables at once (shorthand)

As with the type assignment, all values must have the same data type:

investmentAmount, years, expectedReturnRate := 1000.0, 10.0, 5.5

Last updated