Understanding the compiler: what constant variables can & cannot hold
Published in
Dec 9, 2023
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
- Replicate the error in Rust Playground
- Read more about E0015 and E0010 error codes