Rust – Constants
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 :
Rust
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); } |
Output:
MARKS 100 PI 3.14 NAME GFG
Example 2:
Rust
fn main() { // Declare an integer constant const GFG:i32 = 100; // declaring another constant with same name const GFG:i32 = 200; // printing the value println!( "{}" ,GFG); } |
This will produce an error :