I would like to have:
const COMMANDS_XML: &str = include_str!("../../doc/commands.xml");
const commands_xml: CommandsXml = quick_xml::de::from_str(COMMANDS_XML).unwrap();
As written this does not compile because quick_xml::de::from_str is not a constant function.
I don't particuarly care about the performance difference between building the commands_xml structure at compile time or program startup.
My concern is that this structure is only used in the one file, so I would like to avoid needing to update main() to call an initialize function; as well as needing to pass this structure explicitly to all call points that might call into this module.
How about using a LazyCell?
1 Like
if you want something like C++'s global constructors that get called by the runtime before main, then there's no equivalence in rust: static variables must be initialized with constant value (e.g. as literal or from a const function).
if your data needs to run non-trivial initialization code, then LazyCell can be used for thread locals, as already suggested, or LazyLock should be used for globals that are accessed from multiple threads.
note, "lazyness" means each time the static variable is accessed, it must be checked at runtime whether it is initialized or not, but alternative approaches to this "laziness" require explicit initialization of the value in main, which you say you don't want.
bottom line is, rust does not support global constructors as in C++.
Ha, oops, I was thinking of LazyLock. Linked to the wrong thing.
Thanks, LazyCell seems to be what I was looking for.