Variables in Rust are defined with the let keyword and values are assigned with the = operator. Constants have a similar syntax except they are defined with the const keyword.

// Create a variable and initialize it with a value.
let stuff = "stuff";
let the_answer = 42;

// Explicitly define the type of a variable.
let stuff: &str = "stuff";
let the_answer: i32 = 42;

// Decalre an un-initialized variable without a value.
// The type must be annotated in this case.
let stuff: &str;
let the_answer: i32;

// Assign a value to un-initialized variable.
stuff = "stuff";

// Create a mutable variable with the `mut` keyword.
let mut the_answer = 42;

// Change a mutable variables value.
the_answer = 69;

// Re-declare a variable;
let blah = "blah";
let blah = 69;

// Create a constant, the type must be annotated and value assigned.
const THINGS: &str = "things";


  • Variables are defined in snake_case by convention.
  • Constants are defined in SCREAMING_SNAKE_CASE by convention.
  • Variable types are inferred by the compiler and do not have to be specifically defined in all cases.
  • When an un-initialized variable is declared, it must be assigned a value before it can be accessed.
  • Variables are immutable by default and their value cannot be changed.
  • A variables value cannot be reassigned unless it is marked as being mutable with the mut keyword.
  • A variable is valid during the lifetime of the current block (local scope) which is defined by curly {} brackets.
  • A variables name is unique within the current block and variable shadowing is possible because of this.
  • A variable can be re-declared with the same name during the lifetime of a program.
  • Constants must be defined with their type annotated.
  • A constants value must be an expression that can be determined at compile time.
  • Constants have a lifetime of the current module scope.
  • Constants are accessible in the current module scope.
# rust