There is a special type of variable in Rust, which is called constant.
A constant is a variable that we do not want to change the value of during the whole program.
Creation:
You create a constant variable just like you create a normal one, but adding the keyword const before the variable's type annotation:
const OUR_NAME: &str = "AlgoCademy";
println!("{}", OUR_NAME); // Output: AlgoCademy
Reassignment not allowed:
However, a const variable cannot be reassigned because it is constant. If you try to reassign a const variable, you'll get an error.
For example, this code:
const OUR_NAME: &str = "AlgoCademy";
OUR_NAME = "Andy"; // Here is the problem
would produce error: assignment of read-only variable 'OUR_NAME'
Must be initialized:
Constant variables must be initialized when declared. If you try to declare a const variable without a value, you'll get an error.
For example, this code:
const OUR_NAME: &str;
would produce error: uninitialized const 'OUR_NAME'
Usage:
It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?
The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.
This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.
Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:
const COMPANY_NAME: &str = "Apple";
const FOUNDING_DATE: &str = "April 1st, 1976";
const FOUNDER_NAME: &str = "Steve Jobs";
Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.
I bet you wouldn't love it if a Junior Developer was able to do this successfully:
COMPANY_NAME = "Microsoft";
FOUNDER_NAME = "Bill Gates";
But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.
Assignment
Follow the Coding Tutorial and let's work with constants!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.