How can I get the compiler to warn me of unused code that is marked pub?

匆匆过客 提交于 2020-08-27 08:29:48

问题


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

I have some code marked pub that I know is not being used. How can I get the compiler to warn me of this?

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.


回答1:


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.

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

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.


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.

In similar situations, I've resorted to removing everything public from the API and compiling to see the errors / used functions.



来源:https://stackoverflow.com/questions/51636225/how-can-i-get-the-compiler-to-warn-me-of-unused-code-that-is-marked-pub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!