How to use my own crate


Hi, guys!
I have written a crate and how can I use it in my other program? I am a beginner for Rust. SO anyone could give me the detail instructions?


It really depends on how public your project is. In general, you will just depend on it in your program’s Cargo.toml, and access it with extern crate <name>; just like a library from

If your crate is published in a github repository (or on any other public git server), you can depend on it in Cargo.toml with:

# ...

# ...
my_crate_name = { git = "" }

If your project isn’t on github, you can depend on it with a path dependency:

# ...
my_crate_name = { path = "../my-crate-directory" }

You can adjust the path element to point directly to the directory your crate is in.

After you’ve depended on your crate in Cargo.toml, you can use it in your program with extern crate:

// my-program/src/
extern crate my_crate;

fn main() {
   let x = my_crate::a_function();


Thanks for your answer.

My crate in both source file and binary file is in my local computer. I want to include it in my another Rust program as a local library. For now, I don’t know how to do it. There may need some changes in my Cargo.toml file, I guess, right?


Yep! Cargo can only really add source dependencies, so you will need to add the path of your library crate to the Cargo.toml of the program which is going to use it.

To add one library crate as a dependency so it is accessible from another program, add an entry under [dependencies] as shown:

# Cargo.toml
# ...

# ...
crate_name = { path = "path/to/library/directory/" }

The path can be either relative or absolute - if both rust programs are in the same parent directory, just specify the path as ../name/.

Note that the crate which you want to include as a dependency needs to be a cargo library. It needs its own directory, name, and Cargo.toml to properly access it from another program. If the library is currently a single file, you should create a new cargo directory for it with cargo new <name>, then move the source file to <name>/src/


Thanks so much. I did it as what you said. :laughing: