DEV Community

Nicky Meuleman
Nicky Meuleman

Posted on • Originally published at

Rust: let vs const

To declare a variable in Rust, use the let keyword.

let num = 5;

By default, variables are immutable, you can't change them.
If you wish to mutate it, you have to explicitly state that by adding mut to that declaration.

let mut num = 5;

Now, the number stored in the variable named num may now be changed.

num = 6;

Laurie Barth has an excellent post on mut

Another piece of data that's immutable, (so can't change) is a constant.
Declared with the const keyword.

You might already be familiar with this concept, and wonder:

If variables are immutable by default, what's the difference between variables and constants?
— you (maybe)

  • You aren't allowed to use mut on constants. No mutating, ever.

  • The type of a constant must be declared, whereas the type of a variable may be declared.

  • Constants can only be set to a constant expression, not to the result of a function call or anything that could only be determined at runtime.

As a result, constants are always fixed in size, and known at compile time.

Another, less obvious result, is that constants may not be of a type that requires allocation on the heap, since they're not known at compile time.

  • The naming convention for const is SCREAMING_SNAKE_CASE.
  • The naming convention for let is snake_case.
const SPEED_OF_LIGHT: u32 = 299792458;

Constants can be declared in any scope, including the global scope.

They are valid for the entire runtime of the program inside that scope.

Translation: You can put constants outside of the main function and it will work.

Discussion (0)