- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Constants in Rust Programming
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 −
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 −
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
- Related Articles
- Arrays in Rust Programming
- Casting in Rust Programming
- Channels in Rust Programming
- HashMap in Rust Programming
- HashSet in Rust Programming
- Match in Rust Programming
- Slices in Rust Programming
- Structs in Rust Programming
- Vectors in Rust Programming
- Comments in Rust Programming
- Functions in Rust programming language
- File Operations in Rust Programming
- Loop Keyword in Rust Programming
- Panic! Macro in Rust Programming
- Path Struct in Rust Programming

Advertisements