How do I abstract out a lib with this module?

I am refactoring a project with the goal of spliting it into a lib and a binary. It looks now roughly like this:

├── src
│   ├── lib.rs
│   ├── main.rs
│   └── used_in_lib.rs
│   ├── used_in_main.rs
├── Cargo.lock
├── Cargo.toml
├── .gitignore
├── README.md

Cargo.toml:

[package]
name = "my_package_name"

[dependencies]
# the list goes on

[lib]
name = "my_awesome_lib"

used_in_lib.rs

use my_awesome_lib::{SomeTrait};
// unresolved import `my_awesome_lib`
// use of undeclared crate or module `my_awesome_lib`

pub struct UsedInLib {
    // ...
}

lib.rs

pub mod used_in_lib;

use dependency1;
use dependency2;

pub use used_in_lib::UsedInLib;
// no errors here

pub trait SomeTrait {
    // ...
};

used_in_main.rs

use dependency3;

use my_awesome_lib::SomeTrait; // no error here

main.rs

mod used_in_main

use dependency4;
use dependency5;
use my_awesome_lib; // no error here

use my_awesome_lib::used_in_lib;
// unresolved import `my_awesome_lib::UsedInLib`
// no `used_in_lib` in the root

What am I missing here ? What should I do ? Make a lib directory ? Write a mod.rs file ?

I have searched the documentation but I lack a proper overview here.

You're making cargo compile your lib two times by having the same module declared in both main.rs and lib.rs.

You just need to declare your library modules in lib.rs, using pub as appropriate. And then in your main.rs only use my_lib::{foo, bar};.

So I removed pub use used_in_lib::UsedInLib; from lib.rs but I still get the same errors.

lib.rs

pub mod used_in_lib;

main.rs

use my_lib; // no error
use my_lib::used_in_lib; // unresolved import, no `used_in_lib` in the root

Do you have something like this ?

2 Likes

One thing we missed was in used_in_lib.rs, where

use my_awesome_lib::{SomeTrait};
// should be:
use crate::{SomeTrait};

From then on,

// main.rs
mod my_lib::used_in_lib; // this works

let struct = used_in_lib::SomeStruct { 
    // instantiate
}
// this works

Everything works now, hurray!

BTW thank you @jRimbault for taking the time to even screenshot a proper example.

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.