Cookie Preferences

We use cookies to enhance your experience. Choose your preference for cookie usage.

Essential cookies are required for basic functionality. Additional cookies help us improve our service and provide analytics.

View third-party services
  • Google Analytics: Website traffic analysis and conversion tracking
  • RudderStack: Analysis of user interactions with the website
  • Microsoft Clarity: User behavior analysis & session recordings
  • Facebook Pixel: Marketing analysis of user activity
Test go B 1_

Test go A 1_

13 seconds read

Creating and changing variables and constants are one of the most common operations in many programming languages. You will have to deal with them quite often when you code, so let's learn what they are and how you can 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. If you don't specify the value, the variable will be initialized with the default one:

var variableName type // The default value

It is good practice to assign a variable name that describes its contents.

Always try to choose meaningful and readable names for variables to make your code easy to understand.

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

Please remember that you can assign only a new variable with this operator. It means that you cannot assign a value to the already existing one. In this case, it will throw an error:

fourthNum := 30 
fourthNum = 31 // Ok
fourthNum := 32 // Panic! This variable is already assigned

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

fourthNum, fifthNum := 32, 33 // no panic

Declaring multiple variables

If you don't want to waste line space declaring each variable on a new line, you have two options. First, you can easily declare them on one line:

var python, java, kotlin bool

Second, you can simply declare a block of variables:

var (
    Go         bool
    Dart       bool
    Rust       bool
    TypeScript bool
)

Constants

A constant in Go can be defined with the const keyword, followed by the name and, optionally, 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 ensure that the base value of 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 KremlinTowers = 20
KremlinTowers = 21 // Cannot be assigned to KremlinTowers

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 in the 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 very useful when you have to represent some property for which different distinct values are possible. This is also known as one-hot encoding. Basically, you can use the iota keyword if you have a property and you know it's going to be one-hot encoded. Let's say it has three values: 0, 1, and 2. Then you can write it like this:

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
)

For example, you've got seven days of the week, and you want to define a constant for each day. 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 that is different from Wednesday, and so on. You can put it the following way:

const (
    Monday     = iota
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
    Sunday
)

In this way, the key thing about iota is that it is 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 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 a special iota function used with constants to assign a different value to each of them.

How did you like the theory?
Report a typo