1

I have a rust project with main.rs, some other modules in the main.rs level and several submodules underneath. I use the anyhow crate in almost all of them.

Is there a clean way to declare use anyhow; only once (probably in main.rs?) without the need to redclare its usage in every single mod/file?

Zehanort
  • 458
  • 2
  • 10

2 Answers2

3

Note that anyhow itself should be accessible without use (as of Edition 2018), because this is a crate name. If you mean to import something within that crate for your entire project (use anyhow::Context;), then no, there is no standard¹ way to have that.

Each module has its own scope for such symbols, which are imported via use. The one exception is in the standard preludes, defined by the compiler itself. These are what enable you to use Copy, Result, and others without having to import them explicitly. However, this is naturally out of your control.

There is also a common pattern for some libraries to provide their own prelude: a module that re-exports symbols that are likely to be useful. anyhow does not provide one at the time of writing.

See also:


¹Almost anything becomes possible with macros or another preprocessor, but it is hardly a good tradeoff for this case.

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • 2
    Of note: while anyhow does not provide a prelude, if there are symbols you use everywhere in a program you can have an "internal prelude" which re-exports all the relevant stuff (but is not itself exported in the case of a lib crate). Then, at the top of all your modules you can just `use crate::prelude::*` or something along those lines. – Masklinn Jan 21 '22 at 12:16
0

Rust doesn't support global imports.

However, for global macro imports, there is a way, as explained here. That won't solve your problem completely, but it will at least allow you to avoid importing the macros.

In your main.rs you can add this:

#[macro_use]
extern crate anyhow;

And then you can use macros like bail! and ensure! all around your project, without the need to explicitly import them.

at54321
  • 8,726
  • 26
  • 46