我如何让编译器向我警告标为pub的未使用代码? [英] How can I get the compiler to warn me of unused code that is marked pub?
问题描述
关于未使用的私人物品的锈警告:
Rust warns for unused private items:
warning: function is never used: `hmm`
--> src/example.rs:357:1
|
357 | fn hmm() {
| ^^^^^^^^
|
= note: #[warn(dead_code)] on by default
我有一些代码标记为 pub
的我知道未被使用的地方。
I have some code marked pub
that I know is not being used. How can I get the compiler to warn me of this?
这是在一个库和一系列二进制文件的上下文中,都在同一工作区中的。该库仅由那些二进制文件使用;该库不会被其他任何人占用,并且我也不会上传到crates.io,所以我对所使用的代码有充分的了解。
This is in the context of a library and a series of binaries, all in the same workspace. The library is only used by those binaries; the library isn't being consumed by anybody else and I'm not going to upload to crates.io, so I have full knowledge of the code that's being used.
推荐答案
您无法启用任何功能。根据定义,如果在您的板条箱之外是公共物品,则导入您的板条箱的板条箱可能会使用它;编译器实际上无法告知。这是拥有公共API 的一部分。从公共API中删除某些内容是一项重大更改。
You cannot enable anything to do this. By definition, if something is public outside of your crate, it may be used by the crates that import your crate; there's no way for the compiler to actually tell. This is part of having a public API. Removing something from the public API is a breaking change.
如果您的商品不是从板条箱中导出的,则它是 pub
无关紧要:
If you have an item that's not exported from your crate, the fact that it's pub
won't matter:
mod foo {
pub fn bar() {}
}
fn main() {}
warning: function is never used: `bar`
--> src/main.rs:2:5
|
2 | pub fn bar() {}
| ^^^^^^^^^^^^
|
= note: #[warn(dead_code)] on by default
相反,不要一开始就将其标记为公开。取而代之的是,要么完全放弃 pub
,要么使用像 pub(crate)
这样的可见性修饰符。二进制板条箱基本上应该没有标记为要从板条箱中导出的项目。
Instead, don't mark things as public to start with. Instead, either leave off pub
entirely or use a visibility modifier like pub(crate)
. Binary crates should basically have no items marked for export from the crate.
在您特定的工作空间中,永远不会一个编译器知道所有的时间。例如,如果您的库导出 fn a()
和 fn b()
,而一个二进制文件使用 a
和另一个二进制文件使用 b
,则库的任何编译或任何一个二进制文件都不会看到整个图片。最好的情况是会收到大量的误报。
In your specific case of a workspace, there's never a time when a single compiler knows "everything". For example, if your library exports fn a()
and fn b()
and one binary uses a
and another binary uses b
, then no compilation of the library or either binary would ever see the whole picture. The "best" case would be getting tons of false positives.
在类似情况下,我不得不从API中删除所有公开的 并编译以查看错误/使用的功能。
In similar situations, I've resorted to removing everything public from the API and compiling to see the errors / used functions.
这篇关于我如何让编译器向我警告标为pub的未使用代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!