Applicability of prelude

Hello All,

Can you please clarify if I'm thinking right.
Say I have a program that's structured like this:

project_name
|__ Cargo.toml
|__ src/
    |__ main.rs
    |__ prelude.rs
    |__ products/
    |   |__ mod.rs
    |   |__ prodA.rs
    |   |__ prodB.rs
    |   |__ prodC.rs
    |__ os/
        |__ mod.rs
        |__ os_v1.rs

In all of prodA, prodB, prodC, os_v1 files, I use some functions commonly.
Am I right in putting them all in prelude.rs, so that Rust automatically inserts the mod crate::prelude statements into the above listed files?

Does this make sense?
If so, is this the right way of doing it?

Thanks as always!

You're right that you can define your own prelude, you're wrong in that it won't be imported automatically. Only the standard library prelude is added automatically. You'll still have to use crate::prelude::* in your other modules. A prelude module is just a module like any other, by convention it's been used to denote a group of base functionality a crate would offer.

5 Likes

@kekronbekron

In particular, this convention is AFAIK more a convention of external API than internal use. I.e. if you write a library crate then you can have a module called prelude that users of your library are supposed to import with use library_crate_name::prelude::*; if they want to get the most common/important things into scope. E.g. the futures crate has a prelude like this (which happens to only include traits since traits can be annoying when they’re not in scope because then the type that implement them are “missing” some of their methods provided via those traits). For another example, the gtk crate has a prelude too (which consists mostly of traits as well).

If you want some common functionality in your crate then you can just put it into whatever module you like, no need to call it prelude necessarily. OTOH, feel free to call it prelude if you like. Yours seems to be a binary crate (i.e. no library crate) anyway, so you can follow whatever convention or approach you prefer.

5 Likes

Hmm.. thank you both!
I'll try marking both as solutions lol.

That won’t work :wink:. There can only be one.

Side note: remember that for any given name and source code file name.rs, you should have only one statement mod name; across your whole project. If you want to refer to an item in name.rs from multiple other files in your code, the keyword for importing something under a specific name is use, as in use crate::name::MyType.

2 Likes

So in my case, it'll be use crate::funcs::* in the individual 'adjacent' files, and perhaps mod funcs in main.rs ?

Yep!

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.