Rust Constants Exploration

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we are introduced to the concept of constants in Rust, which can be declared using either const or static keywords, with explicit type annotations, and can be accessed in any scope, including the global scope.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/constants_usage("`Constants Usage`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") subgraph Lab Skills rust/variable_declarations -.-> lab-99275{{"`Rust Constants Exploration`"}} rust/constants_usage -.-> lab-99275{{"`Rust Constants Exploration`"}} rust/integer_types -.-> lab-99275{{"`Rust Constants Exploration`"}} rust/string_type -.-> lab-99275{{"`Rust Constants Exploration`"}} rust/function_syntax -.-> lab-99275{{"`Rust Constants Exploration`"}} rust/expressions_statements -.-> lab-99275{{"`Rust Constants Exploration`"}} end

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. The static lifetime is inferred and does not have to be specified. Accessing or modifying a mutable static variable is unsafe.
// Globals are declared outside all other scopes.
static LANGUAGE: &str = "Rust";
const THRESHOLD: i32 = 10;

fn is_big(n: i32) -> bool {
    // Access constant in some function
    n > THRESHOLD
}

fn main() {
    let n = 16;

    // Access constant in the main thread
    println!("This is {}", LANGUAGE);
    println!("The threshold is {}", THRESHOLD);
    println!("{} is {}", n, if is_big(n) { "big" } else { "small" });

    // Error! Cannot modify a `const`.
    THRESHOLD = 5;
    // FIXME ^ Comment out this line
}

Summary

Congratulations! You have completed the Constants lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like