Instagram
youtube
Facebook
Twitter

Variables and Constants

Variable

  • In Rust, we declare variables first and initialize them later. In Rust, variables are declared by let keyword followed by the variable name that you simply wish to declare.
  • In Rust, variables are immutable by default. This is just one of the numerous suggestions Rust makes to help you build code that takes advantage of Rust's safety and complexity..
let <name> : <type>;

           Or

let <name> = <value>
fn main() {
    let mut x = 45; // i32

    let y: i64 = 81; //i64

    // floating point numbers 
    let _f: f32 = 6.7;
    

    let _b: bool = false;

    println!("y: {}", y);
    println!("The value of x is {}", x);

    x = 60;

    println!("The value of x is {}", x);

}

Constants

  • Constants are non-changeable literals whose values cannot be changed at the time of execution of the program.
const <name> = <value>;
  • By convention, constant names are always preferred in uppercase.

Shadowing

  • Shadowing is a concept in which we can re-declare and reuse the same variable in the same scope.

  • It can be reassigned with a new type and value. The variable name in the following example is declared.  This variable has been renamed and a new value has been assigned to it.

    Example:
    fn main() {
        let x = 12;
    
        {
            let x = 15;
            println!("value of x is {}", x);
        }
    
        let x = 13;
        println!("value of x is {}", x);
    
        let x = "Yaman";
        println!("value of x is {}", x);
    }