Constants with const
- Rust course
- Beginner
- Lesson 9/115
- 4 min
Define compile-time constants with const.
const constants
const is for values known at compile time that never change. Its type is always written explicitly and its name is conventionally in UPPER_CASE:
const MAKS_PUAN: u32 = 100;
const KDV: f64 = 0.20;
fn main() {
println!("{}", MAKS_PUAN);
}Constants can be defined outside functions (globally) and the compiler inlines their value wherever they are used.
const vs let
let can compute its value at run time (let n = read();); const only takes expressions computable at compile time (literals, arithmetic, const fn calls). There is no mut for const. Turning magic numbers (0.20, 100) into named constants makes code readable.
Practice VAT calculation
Define the constant const KDV: f64 = 0.20;. In main, compute the price with VAT for let fiyat = 250.0; and print it with println!("{:.2}", ...).
Starter code
fn main() {
// buraya yaz
}Sample solution
const KDV: f64 = 0.20;
fn main() {
let fiyat = 250.0;
println!("{:.2}", fiyat * (1.0 + KDV));
}Expected output
300.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>const N = 10;</code> compile?
- The name must be lower case
- 10 can't be a constant
- It compiles
- A const must have an explicit type Correct answer
Explanation: Unlike let, const doesn't infer types; you must write const N: i32 = 10;.
2 Constant definition
____ SANIYE_SAAT: u32 = 60 * 60;
const SANIYE_SAAT: u32 = 60 * 60;
Explanation: const defines a value computed at compile time that never changes.
3 Property
| Term | Meaning |
|---|---|
const |
Compile time, type required |
let |
Run time, type inferred |
SCREAMING_CASE |
Constant naming convention |
const fn |
Callable in a constant |