You can use lazy_static for this purpose:
lazy_static! { static ref defs: Vec<String> = { let mut init = vec!["One".to_string(), "Two".to_string()];
This initializes the vector on first access, and after that it is unchanged. If you want to change it later, then ending it in std::sync::Mutex is a good first step.
Are there other patterns that I should consider to support this use case? Passing explicit references to the state vector is possible, but it will clutter up a very large number of function signatures that all need access to this state.
One template to consider is the creation of a context object that stores all the information necessary for functions, for example.
struct Context { defs: Vec<String> }
and then going around Context ensures that everyone knows what they need to know. You might even consider including all / many / some functions as methods on Context , for example.
impl Context { fn foo(&self) { if self.defs.len() > 10 { println!("lots of defs"); } }
This template is especially good if you need to change the context (automatically ensures thread safety) and / or if you want to have several independent instances in one process.
source share