Modules Cause False Unused Code Warnings

This is my first Rust project and as I have begun to split the code into separate module files, the compiler has started to spit out false warnings of unused code.

Minimal Example:

pub struct Settings {
    pub hello: String

pub fn read() -> Settings {
    Settings { hello: "Hello World!".to_string() }

#[path = ""] mod settings;

pub fn print(settings: crate::settings::Settings) {
    println!("{}", settings.hello);

mod settings;
mod client;

fn main() {
    let settings = settings::read();

cargo run:

warning: struct is never constructed: `Settings`
 --> hello\src\
1 | pub struct Settings {
  |            ^^^^^^^^
  = note: `#[warn(dead_code)]` on by default

warning: function is never used: `read`
 --> hello\src\
5 | pub fn read() -> Settings {
  |        ^^^^

warning: 2 warnings emitted

    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
 Running `...\target\debug\hello.exe`
Hello World!

In my real code I'm using the struct from settings in both main and client and am only getting an error for the read function being unused. Why am I getting the unused error(s)? The code is used.


In your case you've actually created the settings module twice – once as hello::settings and once as hello::client::settings.

Remember, in Rust mod declares a module, and you should declare each module exactly once. Exactly like you declare each struct, enum or fn just once.

I think you can just remove this line #[path = ""] mod settings; and it should work. Also, check out this module explanation:

Thank you, that helped immensely, I didn't realize you could only declare/add a module file once in a project and that once settings was declared/included in, it didn't or rather shouldn't be added again in, but can be used as-is.

Reading the link you provided helped me understand the why and come to the same solution.
Removing the line you suggested, and it compiles and runs without errors.

Thank you.


1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.