简体   繁体   English

如何在`main.rs`中声明一个对整体可见的`use`?

[英]How to declare a `use` in `main.rs` that is visible to the whole?

I have a rust project with main.rs , some other modules in the main.rs level and several submodules underneath.我有一个 rust 项目,其中包含main.rsmain.rs级别的其他一些模块以及下面的几个子模块。 I use the anyhow crate in almost all of them.我几乎在所有这些中都使用了anyhow板条箱。

Is there a clean way to declare use anyhow;有没有一种干净的方式来声明use anyhow; only once (probably in main.rs ?) without the need to redclare its usage in every single mod/file?只有一次(可能在main.rs中?)而不需要在每个模块/文件中重新声明它的用法?

Note that anyhow itself should be accessible without use (as of Edition 2018), because this is a crate name.请注意, anyhow ,它本身应该可以在不use的情况下访问(截至 2018 版),因为这是一个 crate 名称。 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.如果您打算在整个项目的箱子中导入某些东西( use anyhow::Context; ),那么不,没有标准的¹方法可以做到这一点。

Each module has its own scope for such symbols, which are imported via use .每个模块都有自己的 scope 用于此类符号,这些符号是通过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.这些使您能够使用CopyResult和其他内容,而无需显式导入它们。 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. anyhow ,在撰写本文时没有提供。

See also:也可以看看:


¹Almost anything becomes possible with macros or another preprocessor, but it is hardly a good tradeoff for this case. ¹使用宏或其他预处理器几乎可以实现任何事情,但对于这种情况来说,这并不是一个好的折衷方案。

Rust doesn't support global imports. Rust 不支持全局导入。

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:在您的main.rs中,您可以添加以下内容:

#[macro_use]
extern crate anyhow;

And then you can use macros like bail!然后你可以使用像bail! and ensure!ensure! all around your project, without the need to explicitly import them.在您的项目周围,无需显式导入它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM