Understanding the compiler: what constant variables can & cannot hold

Generated with AI

Let’s say we want to generate sequences with point mutations at random locations based on a wild type sequence. We decide to store this wild type sequence as a constant.

The following code will result in a compiler error because constants cannot hold anything that is stored on heap memory.

fn main() {
const WILDTYPE_SEQ: String = String::from("ACGT");
println!("{}", WILDTYPE_SEQ);
}

This is the correct way

fn main() {
const WILDTYPE_SEQ: &str = "ACGT";
println!("{}", WILDTYPE_SEQ);
}

Some other facts about constant variables in Rust

  • They can be declared in any scope
  • They must have explicit type annotations
  • They are immutable and cannot be shadowed by other variables with the same name

Next Steps

--

--

Drashti Shah
Bioinformatics with Rust

ESG & climate data scientist by day. Aspiring computational biologist and game designer by night. A Rust fan who believes in an "open career".