-1

what's different let and const in rust ?
for example if use let without mut, is not possible change value

fn main(){
      let MYINT = 1;
      MYINT = 2; // error 

      const MYINT_ = 1;
      MYINT_ = 1; //error
}
F.S
  • 98
  • 8

1 Answers1

4

const indicates a compile-time constant which means it can only be set to a value that can be computed at compile time, e.g. a literal or the result of calling a const fn.

let (without mut) indicates a run-time constant which means it can be initialized from the result of any valid expression.

As to the difference in behavior of the two, you can use const variables in contexts that require compile-time evaluation, such as the length of arrays. You cannot use let variables in these contexts. For example:

fn main() {
    const x: usize = 5;
    let x_arr = [0i32; x];
}

This compiles successfully, and x_arr has type [i32; 5].

fn main() {
    let x: usize = 5;
    let x_arr = [0; x]; // E0435
}

This fails to compile; x cannot be used as an array length as the value must be known at compile time, and x is not a compile-time constant.

error[E0435]: attempt to use a non-constant value in a constant
cdhowie
  • 158,093
  • 24
  • 286
  • 300