Constants are symbolic names that refer to fixed values, that is: values that cannot be changed during the execution of the program. In this lesson we will learn:
- What is a constant?
- How to declare a constant?
- When to use a constant?
1. What is a constant?
In the previous lesson, we learned that variables are memory locations that can be assigned new values later. If you remember the inn rooms analogy: the area of the room would be a constant in a typical program. That is : the area does not change, so it is a good programming habit to declare unchanging values as constants.
Other values that can be declared as constants are : π and the Euler number e in math, the speed of light c in physics, the area of Russia..etc.
2. How to declare a constant?
Constant declaration is pretty straightforward in Go, use the following syntax:
const pi = 3.141592
The compiler will guess the type of the pi constant. You can also declare many constants either by using the keyword const for every constant, or group all constants in one declaration:
/*This */
const pi = 3.141592
const e = 2.718281
/* is equivalent to this*/
const(
pi = 3.141592
e = 2.718281
)
You mostly want to use the second syntax for constants that are related (here, mathematical constants).
3. When to use a constant?
Suppose that you have a very long and exhausting string or number to type every time, like Pi in the previous example : 3.141592..., or the URL of your website, or the name of the 'uploads' folder, or the database password... Then it is better to consider a constant for that.
Because, suppose that you somehow wanted to change the URL of your website, rename the 'uploads/' folder to 'files/', change the database password, or approximate Pi to 10 digits instead of 6...etc. You do not want to replace every occurrence in a large project, that would cost you some time, and possibly, cause bugs and errors.
So, to avoid this situation, it is always better practice to declare constants in a file that is easily accessible (like parameters.go or config.go).
That's mainly why constants are used, they are a way to separate business logic and functions, from values like 'uploads' or '3.14" or "http://example.com/" .
That's it for this lesson, in the next lesson we will learn about naming and visibility in Go .