Skip to content
Related Articles

Related Articles

Rust – Constants

View Discussion
Improve Article
Save Article
  • Last Updated : 31 Mar, 2021

Constants are the value that can not be changed after assigning them. If we created a constant, then there is no way of changing its value. The keyword for declaring constant is const. In Rust, constants must be explicitly typed.  The below syntax is used to initialize a constant value:

Syntax :

const VARIABLE_NAME:dataType = value;

Now let’s check out some examples for the same.

Example 1 :


fn main() {
   // Declare an integer constant
   const MARKS:i32 = 100;
   // Declare a float constant
   const PI:f32 = 3.14;  
   // Declare a string constant
   const NAME:&str = "GFG";
   // display constants
   println!("MARKS {}",MARKS);  
   println!("PI {}",PI);     
   println!("NAME {}",NAME);


PI 3.14

Example 2


fn main() {
  // Declare an integer constant
   const GFG:i32 = 100;
  // declaring another constant with same name
  const GFG:i32 = 200;
  // printing the value

This will produce an error :

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!