How to define complicated lazy_static data without cloning

I've got some static data tables that are embedded in each other, but are using complex data types (eg. BTreeMap). I'm trying to see if there is a way to avoid cloning data when I'm defining all these tables, but I've had no luck so far. Here is a simplification of what I'm doing:

Playground using clone()

In a nutshell, I have:

struct Table { data: [...] }
struct Catalog { tables: BTreeMap<usize, Table> }
struct Directory { catalogs: BTreeMap<usize, Catalog> }

where there will be a number of Catalogs which are used variously by a large number of Directories. I'm using lazy_static to define the Catalogs and Directories, but when defining each Directory I find I have to clone() the Catalogs which appear in more than one Directory.

Given that the data never changes, and that so much of it is duplicated (in my real use-case), I'm trying to see a way to compile it in, but avoid making multiple copies of the various Catalogs, if at all possible.

I feel as though I should be able to do something by storing static references to the Catalogs in the Directories, but I haven't been able to see a way get those static references from lazy_static refs, while defining another lazy_static ref.

Is there something I'm missing, or an different appoach I should be looking at to solve this sort of situation cleanly? Any advice appreciated.

  • Liam

&*THE_CATALOG. When using lazy_static, you actually get a static type that implements Deref to your type (Catalog), and a static of that type. They share the name you give in the macro call.

(Tip: under Tools, you can Expand Macros.)


Thank you for that! I figured it would exactly be something pretty straight-forward that I hadn't tried!

This is one of the first things in the crate docs.

It's been a while since I directly referred to the docs, I admit. I should always go back there first. Thanks for the reminder.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.