6 minutes read

Declaring constants and variables is among the most common operations in many programming languages. You will have to deal with them often when you code, so let's learn what they are and how to use them.

A variable is a named place in memory where you can store data to access it later. It's like a box with a gift inside: you can consider it a kind of variable too!

Every variable has a name to distinguish it from other variables. It is possible to access a value by its name.

Declaring a variable

You can use the var keyword, followed by the variable name and type to declare a variable in Go:

var variableName variableType

Variables declared without an explicit initial value are given their default or zero value. Below you can see the zero value for each data type:

var i int     // 0
var f float64 // 0 
var b bool    // false 
var s string  // ""

Generally, giving a variable a meaningful name that describes its content is a good coding practice.

Now, we can declare a variable and assign a value to it:

var firstNum int = 1

For some data types, it is possible to skip the type, as the compiler will detect it automatically:

var secondNum = 20 // Skipping the type

You can also use := in statements. It is a declare and assign construction:

thirdNum := 30

Note that the := operator is exclusively used to declare and assign new variables. It means that you cannot use it to reassign values to existing variables alone; doing so will lead to a compile-time error:

fourthNum := 30
fourthNum = 31  // OK — Assign a new value `31` to `fourthNum` 
fourthNum := 32 // compile-time error! This variable is already declared

However, if you add a new variable, there will be no error:

fourthNum, fifthNum := 32, 33 // no compile-time error

Declaring multiple variables

You can easily declare multiple variables of the same type on one line:

var isEnabled, hasValues, isOrdered bool

And to declare multiple variables of different types, you can use a block of variables:

var (
    isEnabled bool
    hasValues bool
    isOrdered bool
    firstNum  int
    hello     string
)

Constants

A constant in Go can be defined with the const keyword, followed by the name and, optionally, the type of the constant:

const pi = 3.141
const hubble int = 77

You can declare a block of constants at once without having to specify a keyword before each constant:

const ( 
    hello = "Hello" 
    e = 2.718
)

Constants have several advantages over variables. They make your code more readable and ensure that a specific value in the code remains unchanged. It doesn't matter much for small projects, but it certainly does for larger ones with numerous components contributed by multiple authors.

Besides, constants give the compiler a strong cue for optimization. Since the compiler knows that the value cannot be changed, it doesn't need to load the value from memory each time, and it can optimize the code to work only for the exact value of the constant.

const HoursPerDay = 24
HoursPerDay = 25 // Cannot be assigned to `HoursPerDay`

Moreover, constants can also serve as a defensive measure to protect you from yourself: for example, from accidentally changing a value somewhere in the code when you're working late at night or before you've had your coffee early in the morning.

Iota

The iota keyword is a handy auto-increment that generates constants. It constructs a set of related but distinct constants starting from 0.

It proves useful when you have to represent some property for which different distinct values are possible. To better explain how the auto-increment property of iota works, let's take a look at the following example:

const (
    A = iota  // 0
    B = iota  // 1
    C = iota  // 2
)

This step can be simplified as follows:

const (
    A = iota // 0
    B        // 1
    C        // 2
)

It is also possible to skip values of iota via the _ = iota syntax; however, take notice that only the underscore _ character will skip the value. For example, suppose you wanted to skip the 0 and 2 values:

const (
    _ = iota // Skip 0
    A        // 1
    _        // Skip 2
    B        // 3
    C        // 4
)

A simple use case for iota would be if you wanted to define a constant for each day of the week. In this case, you want them all to be constants with different values. However, it doesn't matter what exact value each constant has as long as Monday is different from Tuesday, which is different from Wednesday, and so on. You can write it the following way:

const (
    Monday    = iota + 1 // Start from 1 instead of 0
    Tuesday              // 2
    Wednesday            // 3
    Thursday             // 4
    Friday               // 5
    Saturday             // 6
    Sunday               // 7
)

Take notice that the iota + 1 syntax makes the auto-increment start from 1 instead of 0. As you can see,iota provides a convenient way to generate different constants when the actual constant values are not that important.

This is essentially a standard enumeration, like in other programming languages.

One of the common uses of iota is when we work with bitmasks and want to change the permission of the files, like this:

const (
    Read = 1 << iota  // << A bit operation
    Write
    Execute
)

Another way to do this is to make an enumeration, like in other languages, which we will cover in further topics.

Conclusion

Variables and constants appear in every high-level language, and in this topic, you've learned how to declare and assign values to them in Go. You've also got to know about the unique iota keyword used with constants to give an incrementing value to each of them.

183 learners liked this piece of theory. 6 didn't like it. What about you?
Report a typo