Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is different let ( without mut ) with const

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading