How to have a library with multiple features?

I would like to create a small library that is used by a few microservices internally.

Cargo.toml

[features]
auth = []
eid = []
time = []

lib.rs

#[cfg(feature = "auth")]
pub mod auth;
#[cfg(feature = "eid")]
pub mod eid;
#[cfg(feature = "time")]
pub mod time;

Error:

   Compiling datafet v0.3.2 (code/libraries/)
error[E0432]: unresolved import `eid`
  --> src/lib.rs:13:9
   |
13 |     use eid::{get_db_eid, get_job_eid, get_query_eid, get_table_eid};
   |         ^^^ use of undeclared crate or module `eid`

error[E0432]: unresolved import `time`
  --> src/lib.rs:14:9
   |
14 |     use time::utc_now;
   |         ^^^^ help: a similar path exists: `std::time`

For more information about this error, try `rustc --explain E0432`.
error: could not compile `d` due to 2 previous errors

 *  The terminal process "cargo 'test', '--package', 'd', '--lib', '--', 'tests', '--nocapture'" failed to launch (exit code: 101). 
 *  Terminal will be reused by tasks, press any key to close it. 

lib.rs test section:

#[cfg(test)]
mod tests {

    use eid::{get_db_eid, get_job_eid, get_query_eid, get_table_eid};
    use time::utc_now;

    #[test]
    fn test_get_db_eid() {
        let result = get_db_eid("example");
        assert_eq!(result, "db-mntdkyjymnsdqojyg4ywmnlfgu".to_string());
    }

I think I am missing something.

Your use items need to have the same cfgs on them that the pub mod items do.

If you're just trying to enable the features for tests, you need to pass the features on the command line to cargo test right now

1 Like

Your use items need to have the same cfg s on them that the pub mod items do.

One way to to do this is to put the tests module inside the already cfg-ed module — in this case, tests for eid would go inside a mod tests { inside src/eid.rs.

2 Likes

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.