The Cargo web site provides a good explanation of how to use Cargo with external libraries found on GitHub but it does not give any examples of how to use libraries or crates which are local projects.

Today I came upon a question on StackOverflow asking how to do this. I had also created an issue on GitHub relating to this, so I decided to write this post.

Basic project structure

These instructions assume that you are using the default Cargo project structure which is initialized when you call cargo new project-name.

If you added your Cargo.toml file after creating your project you can conform to the Cargo structure by moving your sources in a src/ folder, creating a lib.rs in project-name/src/ and putting your Cargo.toml file under project-name/.

For the project’s structure here’s what you’ll end up with where project is the name of your project and local_dependency the name of your component/sub-project.

project/
├── Cargo.toml
├── src
│   ├── local_dependency
│   │   ├── Cargo.toml
│   │   ├── lib.rs
│   │   └── source_file.rs
│   ├── lib.rs
│   └── main.rs

Your Cargo.toml in your main project’s root should look like this:

[package]
name = "project"
version = "0.0.1"
authors = ["That guy over there!"]

[dependencies.local_dependency]
path = "src/local_dependency"

Since your local dependency is a separate project it will need it’s own Cargo.toml file which will should like this:

[package]
name = "local_dependency"
version = "0.0.1"
authors = ["Somebody else"]

[lib]
name = "local_dependency"
path = "lib.rs"

The lib.rs in src/local_dependency/ will contain the public declarations of your modules.

pub use source_file::SomethingUseful;

pub mod source_file;
 

For reference here is source_file.rs:

pub enum SomethingUseful {
    Really,
    Nah
}

The lib.rs file in src/ is the library file for your main program which you leave empty until you need it.

Finally, in your main source file (src/main.rs) you can reference parts of your local dependency likewise:

extern crate local_dependency;

use local_dependency::SomethingUseful;

fn main() {
    println!("Hello world!")
}

Here you go.

4 thoughts on “Using a local crate with Cargo

Leave a comment