In programming, a variable is a container that is used to store data. Here's how we can declare a variable in Go programming.
In Go, every variable has a fixed data type associated with it. The data type determines the type of data that the variable can store. For example, the number variable can only store integer data. It's because its type is int. We will learn about different types of data types in detail in the next tutorial.
There are 3 ways to assign values to a variable.
Here, we have assigned an integer value 10 to the number variable.
Here, we are not explicitly specifying the data type of the variable. In this case, the compiler automatically detects the type by looking at the value of the variable.
Since the value 10 is an integer, the data type of number is int.
Here, we are using the := operator to assign the value 10 to the variable number. This is the shorthand notation to assign values to variables.
For example:
Here, the count variable prints 0 (default value for int) because we haven't assigned any value to it.
Output
As suggested by the name variable, we can change the value stored in a variable. For example:
Initially, 10 was stored in the variable. Then, its value is changed to 100.
In Go, we cannot change the type of variables after it is declared. In the above example, the number variable can only store integer values. It cannot be used to store other types of data. For example:
In Go, it's also possible to declare multiple variables at once by separating them with commas. For example:
Here, "Palistha" is assigned to the name variable. Similarly, 22 is assigned to the age variable.
The same code above can also be written as:
A variable name consists of alphabets, digits, and an underscore.
Variables cannot have other symbols ( $, @, #, etc).
Variable names cannot begin with a number.
A variable name cannot be a reserved word as they are part of the Go syntax like int, type, for, etc.
By the way, we should always try to give meaningful variable names. This makes your code easier to read and understand.
| Illegal Variable | Bad Variable | Good Variable |
|---|---|---|
| 1a | a | age |
| s@lary | sal | salary |
| first name | fn | firstName |
| annual-income | annInc | annualIncome |
Constants are the fixed values that cannot be changed once declared. In Go, we use the const keyword to create constant variables. For example,
By the way, we cannot use the shorthand notation := to create constants. For example,