-
Book Overview & Buying
-
Table Of Contents
Design Patterns and Best Practices in Rust
By :
The Flyweight pattern minimizes memory usage by sharing common data across multiple objects. In languages where object allocation is expensive and objects carry significant overhead, flyweight factories that cache and reuse shared state can provide substantial savings. In Rust, however, the language and standard library provide built-in mechanisms that serve the same purpose, often more safely and efficiently than a hand-written flyweight implementation.
The most direct flyweight mechanism in Rust is the use of const and static values. Mathematical constants that many expressions share can be defined once and referenced everywhere:
pub const DEFAULT_PRECISION: u32 = 10;
pub const MAX_PRECISION: u32 = 100;
static CONFIG: OnceLock<CalculatorConfig> =
OnceLock::new();
pub fn get_global_config() -> &'static CalculatorConfig {
CONFIG.get_or_init(|| CalculatorConfig::default())
}
The OnceLock ensures the configuration is initialized exactly...