Organizing Your Imports With a Prelude

Hands-on Rust — by Herbert Wolverson (44 / 120)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Dividing Your Code Into Modules | TOC | Storing the Dungeon Map 👉

Prefixing every map access with map:: or crate::map:: is unwieldy and will get more cumbersome as you add more modules. When you access a Rust library, it’s common for the library author to have placed everything you need in a convenient prelude. You used bracket-lib’s prelude in Hello, Bracket Terminal. You can simplify module access by making your own prelude to export common functionality to the rest of the program. Add the following to your main.rs file:

BasicDungeonCrawler/dungeon_crawl_map/src/main.rs

​​①​​mod​ map; 

​​②​​mod​ prelude {
​​③​ ​pub​ ​use​ ​bracket_lib​::​prelude​::*;
​​④​ ​pub​ ​const​ SCREEN_WIDTH: i32 = 80;
​ ​pub​ ​const​ SCREEN_HEIGHT: i32 = 50;
​​⑤​ ​pub​ ​use​ ​crate​::​map​::*;
​ }

​​⑥​​use​ ​prelude​::*;

​①​
Add the module to your project with mod.

​②​
The mod keyword can also be used to declare a new module in your source code. Because this is the top level of your crate, you don’t need to make it public — modules branching from crate are visible throughout your program.

​③​
Publicly using the bracket_lib prelude re-exports it inside your prelude. Anything that uses your prelude also uses bracket_lib.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.