constants

Rust has two different types of constants which can be declared in any scope
including global. Both require explicit type annotation:

  • const: An unchangeable value (the common case).
  • static: A possibly mutable variable with 'static lifetime.

One special case is the "string" literal. It can be assigned directly to a
static variable without modification because its type signature:
&'static str has the required lifetime of 'static. All other reference
types must be specifically annotated so that they fulfill the 'static
lifetime. This may seem minor though because the required explicit annotation
hides the distinction.

  1. // Globals are declared outside all other scopes.
  2. static LANGUAGE: &'static str = "Rust";
  3. const THRESHOLD: i32 = 10;
  4. fn is_big(n: i32) -> bool {
  5. // Access constant in some function
  6. n > THRESHOLD
  7. }
  8. fn main() {
  9. let n = 16;
  10. // Access constant in the main thread
  11. println!("This is {}", LANGUAGE);
  12. println!("The threshold is {}", THRESHOLD);
  13. println!("{} is {}", n, if is_big(n) { "big" } else { "small" });
  14. // Error! Cannot modify a `const`.
  15. THRESHOLD = 5;
  16. // FIXME ^ Comment out this line
  17. }

See also:

The const/static RFC,
'static lifetime