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:

settings.rs:

pub struct Settings {
    pub hello: String
}

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

client.rs:

#[path = "settings.rs"] mod settings;

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

main.rs:

mod settings;
mod client;

fn main() {
    let settings = settings::read();
	client::print(settings);
}

cargo run:

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

warning: function is never used: `read`
 --> hello\src\settings.rs:5:8
  |
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.

Peter

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 = "settings.rs"] 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 main.rs, it didn't or rather shouldn't be added again in client.rs, 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.

Peter

1 Like