Sometimes, it’s handy to have a few instances of a struct
stored and accessible everywhere.
For instance, if I want to store some meta-data about a currency in a struct like this:
struct Currency {
name: &'static str,
iso_symbols: Vec<&'static str>
}
I would then create an instance of Currency
for every major currency. As these property don’t change, it could be hard-coded, at least for some currencies.
I tried to use const
, which would work without a Vec (the vec!
macro does an allocation, which is not allowed in const
).
const BTC: Currency = Currency {
name: "Bitcoin",
iso_symbols: vec!["BTC", "XBT"]
};
So what workaround would you suggest to store a bunch of instance of Currency
(for EUR, USD, BTC…)?
Here, in the Rust Playground.
EDIT: My question is quite similar to this one. The only difference is that I don’t need a mutable singleton, so the “Non-answer answer” doesn’t apply, right? The lazy_static
idea is great though!
It might be interesting to keep this question around since I didn’t searched with the keyword singleton
and I may not be alone to miss this way to consider the problem.