Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use external crates in Rust?

Tags:

libraries

rust

I'm trying to work with the rust-http library, and I'd like to use it as the basis for a small project.

I have no idea how to use something that I can't install via rustpkg install <remote_url>. In fact, I found out today that rustpkg is now deprecated.

If I git clone the library and run the appropriate make commands to get it built, how do I use it elsewhere? I.e. how do I actually use extern crate http?

like image 340
lucperkins Avatar asked Feb 09 '14 03:02

lucperkins


People also ask

What is an external crate Rust?

An external crate means "someone else's crate". For this section you almost need to install Rust, but we can still use just the Playground. Now we are going to learn how to import crates that other people have written. This is important in Rust because of two reasons: It is very easy to import other crates, and.

How do you use packages in Rust?

Cargo Create Package In the root directory of the package_name, you will find the Cargo. toml file which is a default config file generated by cargo. The next is the src directory, which contains the source code for your application. By default, cargo will add main.rs file with a hello world program.

Is extern crate necessary?

Here's a brief summary: extern crate is no longer needed in 99% of circumstances. The crate keyword refers to the current crate.


2 Answers

Since Rust 1.0, 99% of all users will use Cargo to manage the dependencies of a project. The TL;DR of the documentation is:

  1. Create a project using cargo new

  2. Edit the generated Cargo.toml file to add dependencies:

    [dependencies] old-http = "0.1.0-pre" 
  3. Access the crate in your code:

    Rust 2021 and 2018

    use old_http::SomeType; 

    Rust 2015

    extern crate old_http; use old_http::SomeType; 
  4. Build the project with cargo build

Cargo will take care of managing the versions, building the dependencies when needed, and passing the correct arguments to the compiler to link together all of the dependencies.

Read The Rust Programming Language for further details on getting started with Cargo. Specifying Dependencies in the Cargo book has details about what kinds of dependencies you can add.

like image 120
Shepmaster Avatar answered Oct 06 '22 01:10

Shepmaster


Update

For modern Rust, see this answer.


Original answer

You need to pass the -L flag to rustc to add the directory which contains the compiled http library to the search path. Something like rustc -L path-to-cloned-rust-http-repo/build your-source-file.rs should do.

Tutorial reference

like image 20
nameless Avatar answered Oct 06 '22 01:10

nameless