So I'm exploring Rust, and I have read about technical differences between constants and immutable variables. But it seems like immutable variables can do all things that constants can. Then what is the point of existence of constants, if immutable variables can fully substitute them?
-
2Does this answer your question? [What is the difference between immutable and const variables in Rust?](https://stackoverflow.com/questions/37877381/what-is-the-difference-between-immutable-and-const-variables-in-rust) – whilrun Jan 18 '22 at 18:02
-
@whilrun they only show the difference, but it doesn't make it clear why we need constants at all. Immutable variables can do same things and even more. – Oleksandr Novik Jan 18 '22 at 18:05
2 Answers
There are two computational times that you should take into account:
- compilation time
- run time
The constant is computed at compilation time (and can be used in other compile-time computation) and hence the run time is faster, as it does need to compute it again.
Immutable variables are always computed at run time (from an external input not available at compulation time usually), and constants cannot be used there.
- 1,055
- 1
- 6
- 17
Then what is the point of existence of constants, if immutable variables can fully substitute them?
While there are certainly use cases in which constants may be interchangeable with immutable variables, the main distinction between the categories of values is their semantics.
Declaring a constant immediately says a lot about what the value is to the reader: in particular, that the information that comprises the value must all be available at compile-time. This is a property which is enforced by the compiler. This sets up expectations for the reader about what the value is and what can be done with it.
Of course, the initialization of immutable variables is much more flexible. There is no mandate that these values are known at compile time, and the calculations that produce such values may be arbitrarily complex and even evolve over time.
The differences are, perhaps, mainly stylistic (in many but not all use cases) but where readability and maintainability are involved the distinction is valuable.
- 9,584
- 3
- 39
- 53