Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to code a rust project using a main.rs to lib.rs workflow?

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 document how to implement such a workflow. I frankly have no idea how to even begin.

Could someone either describe how to set up a workflow which makes use of both of these files or direct me to some resources which go through the process start to end and not just assume significant prior knowledge. Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 :

  • declare all modules and pub use in the lib.rs
  • have a main function in your main.rs, running the application

When 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading