Estático y Constantes (Static y Const)

Static and constant variables are two different ways to create globally-scoped values that cannot be moved or reallocated during the execution of the program.

const

Las variables constantes se evalúan en tiempo de compilación y sus valores se insertan dondequiera que se utilicen:

const DIGEST_SIZE: usize = 3;
const ZERO: Option<u8> = Some(42);

fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {
    let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];
    for (idx, &b) in text.as_bytes().iter().enumerate() {
        digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b);
    }
    digest
}

fn main() {
    let digest = compute_digest("Hello");
    println!("digest: {digest:?}");
}

According to the Rust RFC Book these are inlined upon use.

Sólo se pueden llamar a las funciones marcadas como const en tiempo de compilación para generar valores const. Sin embargo, las funciones const se pueden llamar en runtime.

static

Las variables estáticas vivirán durante toda la ejecución del programa y, por lo tanto, no se moverán:

static BANNER: &str = "Welcome to RustOS 3.14";

fn main() {
    println!("{BANNER}");
}

As noted in the Rust RFC Book, these are not inlined upon use and have an actual associated memory location. This is useful for unsafe and embedded code, and the variable lives through the entirety of the program execution. When a globally-scoped value does not have a reason to need object identity, const is generally preferred.

This slide should take about 5 minutes.
  • Menciona que const se comporta semánticamente de forma similar a constexpr de C++.
  • Por su parte, static se parece mucho más a const o a una variable global mutable de C++.
  • static proporciona la identidad del objeto: una dirección en la memoria y en el estado que requieren los tipos con mutabilidad interior, como Mutex<T>.
  • No es muy habitual que se necesite una constante evaluada en runtime, pero es útil y más seguro que usar una estática.

Tabla de Propiedades:

PropiedadEstáticoConstante
Tiene una dirección en la memoriaNo (insertado)
Vive durante toda la ejecución del programaNo
Puede ser mutableSí (inseguro)No
Evaluado en tiempo de compilaciónSí (inicializado en tiempo de compilación)
Insertado dondequiera que se utiliceNo

Más información

Because static variables are accessible from any thread, they must be Sync. Interior mutability is possible through a Mutex, atomic or similar.

Thread-local data can be created with the macro std::thread_local.