Turning off warnings for an unused module

I have a module with a whole bunch of functions and methods that are only called from within the module. There is one function that gets called from outside the module. If I don't call that one function, I get a gazillion dead code warnings. The problem is that I have two mains, one of which makes the call and one that does not. Is there any alternative to turning off the dead code warning for the entire module? I would like to tell the compiler to suppress the warnings if the whole module is dead code, or better yet give me one warning for the whole module.

My current workaround is to put

    if false { foo(); }

in the main that doesn't need to call the function. Unfortunately, that won't work when the function takes parameters that aren't available in the caller.

You can #[allow(dead_code)] on the one "entry point" function, and it'll essentially treat that function as used: Rust Playground


You could always if false { foo(unreachable!(), unreachable!(), ...); }, but it's not pretty.

Besides #[allow(dead_code)], you can make an item (e.g., a whole mod) disappear with #[cfg(any())], which for quick and dirty switching between mains could do the trick.

But the clean way to "switch between mains" is conditional compilation with features:

  • Cargo.toml
default = [
  # "foo-main",  # uncomment to enable the feature by default
foo-main = []
  • src/main.rs
#[cfg(feature = "foo-main")]
mod has_foo;

#[cfg(feature = "foo-main")]
fn main ()

#[cfg(not(feature = "foo-main"))]
fn main ()
  • then, if default = ["foo-main"] in Cargo.toml or if you run cargo with --features foo-main, your program will compile and use the main that calls foo and also the mod it requires;

  • if default = [], or if you run cargo with --no-default-features, your program will compile and use the main that does not call foo, and the unused mod won't be compiled, thus avoiding triggering unused_* lints.

1 Like

Thanks @sfackler. I thought that #[allow(dead_code)] just suppressed the warnings. I did not know that it treated the function as used.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.