Constants in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Rust provides us with two types of constants. These are −

  • const − an unchangeable value
  • static − possible mutable value with static lifetime.

If we try to assign another value to an already declared const value, the compiler will throw an error.

Example

Consider the example shown below −

 Live Demo

static LANGUAGE: &str = "TutorialsPoint-Rust";
const THRESHOLD: i32 = 10;
fn is_small(n: i32) -> bool {
   n < THRESHOLD
}
fn main() {
   // Error! Cannot modify a `const`.
   THRESHOLD = 5;
   println!("Everything worked fine!");
}

In the above code, we are trying to modify the value of a variable that is already declared with a const keyword, which is not allowed.

Output

error[E0070]: invalid left-hand side of assignment
--> src/main.rs:12:15
|
12| THRESHOLD = 5;
| --------- ^
| |
| cannot assign to this expression

We can also access the constants that we declared in other functions.

Example

Consider the example shown below −

 Live Demo

static LANGUAGE: &str = "TutorialsPoint-Rust";
const THRESHOLD: i32 = 11;
fn is_small(n: i32) -> bool {
   n < THRESHOLD
}
fn main() {
   let n = 19;
   println!("This is {}", LANGUAGE);
   println!("The threshold is {}", THRESHOLD);
   println!("{} is {}", n, if is_small(n) { "small" } else { "big" });
}

Output

This is TutorialsPoint-Rust
The threshold is 11
19 is big
raja
Published on 03-Apr-2021 12:42:43
Advertisements