How to use my own crate


#1

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?


#2

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 crates.io.

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:

[package]
# ...

[dependencies]
# ...
my_crate_name = { git = "https://github.com/username/project-name.git" }

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

[dependencies]
# ...
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/main.rs
extern crate my_crate;

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

#4

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?


#5

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
[project]
# ...

[dependencies]
# ...
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/lib.rs.


#6

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