Home Compact module declaration
Post
Cancel

Compact module declaration

Here’s a cool technique how to declare all of a project’s modules inside the project root (typically src/lib.cairo) without any intermediary module files.

Let’s say we have a project where src/ looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.
├── core
│   ├── m1.cairo
│   ├── m2.cario
│   └── m3.cairo
├── lib.cairo
├── tests
│   ├── core
│   │   ├── test_m1.cairo
│   │   ├── test_m2.cairo
│   │   └── test_m3.cairo
│   └── utils
└── utils
    ├── common.cairo
    └── conv.cairo

Instead of having additional files like core.cairo and utils.cairo on the same level as lib.cairo that just declare the inner modules, we can put everything in lib.cairo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mod core {
    mod m1;
    mod m2;
    mod m3;
}

mod utils {
    mod commmon;
    mod conv;
}

#[cfg(test)]
mod tests {
    mod core {
        mod test_m1;
        mod test_m2;
        mod test_m3;
    }
}

They’re the same picture!

To get a better sense of the improvement, let’s have a look at some real world examples. Compare the original, verbose style that’s used in Pragma with the compact one used in Satoru. Notice the additional files in Pragma’s src dir like admin.cairo that are there only to declare mod admin. I definitely like the compact one better.

Shout out to gaetbout for showing me the way.

This post is licensed under CC BY 4.0 by the author.