When writing doctests for methods on a struct or trait or functions in a file, etc. I often find myself putting the same use my_crate::{MyStruct, MyTrait, Etc}
at the beginning of each doctest. Is there any way to avoid this duplication, like some way I could define those use statement just once for the whole module?
Asked
Active
Viewed 50 times
2

Thayne
- 6,619
- 2
- 42
- 67
-
1I wouldn't recommend this, but you could put all the imports in a file, then `include!()` that file in your doctests. – Ivan C Jan 21 '23 at 06:07
-
@IvanC is right that `include!()` would technically be a valid solution, but I also wouldn't recommend it since it decreases the usefulness of your doctests to readers. If you feel that imports are cluttering up your doctests, you also choose to hide those lines so they won't appear in the documentation. https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#hiding-portions-of-the-example – Locke Jan 21 '23 at 06:26
1 Answers
1
If you keep finding the same group of items gets imported over and over again, you may want to consider creating a prelude module. The core idea is that you simply re-export those key items in that module so anyone using your crate can do use your_crate::prelude::*;
to import all of them as a group.
One common use cases for this is if you have a lot of traits that are frequently used. When you provide the most common traits as a group, your users don't need to spend figuring out which traits provide which methods. You can also choose to add structs/enums/unions, but I wouldn't recommend it. Unlike traits, types are almost always referred to explicitly and are much easier to find.
For example, here is what rayon
's prelude module looks like.
//! The rayon prelude imports the various `ParallelIterator` traits.
//! The intention is that one can include `use rayon::prelude::*` and
//! have easy access to the various traits and methods you will need.
pub use crate::iter::FromParallelIterator;
pub use crate::iter::IndexedParallelIterator;
pub use crate::iter::IntoParallelIterator;
pub use crate::iter::IntoParallelRefIterator;
pub use crate::iter::IntoParallelRefMutIterator;
pub use crate::iter::ParallelBridge;
pub use crate::iter::ParallelDrainFull;
pub use crate::iter::ParallelDrainRange;
pub use crate::iter::ParallelExtend;
pub use crate::iter::ParallelIterator;
pub use crate::slice::ParallelSlice;
pub use crate::slice::ParallelSliceMut;
pub use crate::str::ParallelString;

Locke
- 7,626
- 2
- 21
- 41