Module organisation / 'function never used'

Hi all,

I have a question around code or module organization. My simplified setup:

I have a project with 2 bins (defined in the Cargo.toml), each implemented in its own source file. I have a third file, which contains code used by both, imported via a 'mod in both bins.

Now one of them uses only parts of the defined functions, leading to warning while compilation for 'function never used'.

What is the right way to avoid this?

bin1.rs:

mod dau_mod;

use dau_mod::{test_func1, test_func2};

fn main() {

    test_func1();
    test_func2();
}

bin2.rs:

mod dau_mod;

use dau_mod::{test_func1};

fn main() {

    test_func1();
}

dau_mod.rs:

pub fn test_func1(){
    println!("This is test_func1()!");
}

pub fn test_func2() {
    println!("This is test_func2()!");
}
1 Like

When you have two seperate mod declarations, you end up with two separate modules. The typical approach for sharing code between multiple binaries is to make a lib.rs and put the mod declaration there, and then import it from your binary with use your_crate_name::dau_mod::test_func1;

1 Like

For the exact syntax I need to a little bit trial on error..... but got it. For those looking for the exact solution:
bin1.rs:

use dau_mod::{test_func1, test_func2};

fn main() {

    test_func1();
    test_func2();
}

bin2.rs:

use dau_mod::{test_func1};

fn main() {

    test_func1();
}

dau_mod.rs remains the same, but the Cargo.toml is of interest, the important parts:

[lib]
name = "dau_mod"
path = "src/dau_mod.rs"

[[bin]]
name = "bin1"
path = "src/bin1.rs"

[[bin]]
name = "bin2"
path = "src/bin2.rs"

Thanks for the help!

One more hint: if you named the library file lib.rs instead of dau_mod.rs, binaries would use it just the same, and Cargo.toml will not have the path entry in [lib], since this is the default name.

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