Avoid duplicating use statements at beginning of doctests

93 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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;