Reputation: 2479
Many times throughout the Rust documentation, examples pop up which use lib.rs
files. After some research, I understand that it is common practice in the rust community to use main.rs
to point to the lib.rs
file, which would house most of the program's functionality.
My issue is that I haven't been able to find any resources which describe how to connect the lib.rs
to main.rs
.
How do I expose lib.rs
to main.rs
?
Upvotes: 5
Views: 5597
Reputation: 2479
This post here has responses which discuss at it's simplest how to bring stuff from lib.rs
into main.rs
.
Rust modules confusion when there is main.rs and lib.rs
The key thing that I felt connected the dots was the explanation by L.Y Sim that you needed to reference the project's name to expose lib.rs
to main.rs
.
One more thing, if you wanted to access items that are exposed in src/lib.rs from src/main.rs, you have to do as @zrzka said, which is to name the name of the crate that both src/lib.rs and src/main.rs share. For example, in your project which is named hello-world:
use hello_world::foo;
fn main() {
foo::say_foo();
}
Upvotes: 2
Reputation: 382112
The workflow is pretty simple as a project is defined in Rust with only a few files.
When your project has a src/lib.rs
file, then it's a library and can be called by other crates.
When your project has a src/main.rs
file, then it's built into an executable.
And your project can have both, which simplifies exposing functions of your application for other crates.
Here's a small example: rhit, which has both files.
As simple organization :
pub use
in the lib.rsmain
function in your main.rs, running the applicationWhen your core features are more important and may be used in another application, or when the application needs dependencies which are useless for other applications needing your core features, then the alternative should be considered: separate your application in two crates witch clearly distinct roles. You may find this for example in lfs wich uses lfs-core, the latter one being available in other applications which won't import the specific dependencies of lfs.
Upvotes: 6