leshow
leshow

Reputation: 1658

How do I use a new local module?

I'm unable to import and use a module I've written, not sure where I went wrong.

My starting directory structure is:

/src/main.rs <- contains fn main()
/Cargo.toml

I wanted to refactor some code out of one big main file I had, so I ran

cargo new mnemonic

leaving me with:

/src/main.rs <- contains fn main()
/Cargo.toml
/mnemonic/src/lib.rs
/mnemonic/Cargo.toml

in the /mnemonic/src/lib.rs that was created I put:

pub mod mnemonic;

then put my code in /mnemonic/src/mnemonic.rs (has 2 public functions I want to use from main). I ran cargo build from mnemonic/ and back in my main src, I tried

extern crate mnemonic;

and

use mnemonic;

I also tried use mnemonic::mnemonic;

In all instances, it was unable to find the crate or gave an unresolved import error.

I've also tried putting my code containing the 2 pub functions in /src/mnemonic.rs

and in /src/main.rs putting:

use mnemonic;

I also tried just putting my code in mnemonic/src/lib.rs and trying extern crate mnemonic; use mnemonic; from src/main.rs

Am I supposed to edit Cargo.toml in any of the instances you proposed?

Upvotes: 0

Views: 3769

Answers (1)

Shepmaster
Shepmaster

Reputation: 432189

Updated Answer

Yes, you need to tell Cargo where to find your crate. In your binaries Cargo.toml, add something like:

[dependencies.mnemonic]
path = "./mnemonic"

Original Answer

When you create a new crate, it automatically has one layer of namespacing: the name of the crate itself. In addition, you don't need to extern use a crate if it is your current crate!

Using crate mnemonic from other crates

This is probably what you want to do: Create a new crate called mnemonic, then you will have a src/lib.rs. Put your code in there, and you can then use it from other crates with

extern crate mnemonic;
use mnemonic::ItemInLibDotRs; // Make sure this item is marked as `pub`!

Using a nested module mnemonic from the crate mnemonic

Say you have some implementation detail you want to hide from the end user. We will put it in a module within the crate, and use it only from within the same crate.

Put your code in src/mnemonic.rs. In src/lib.rs, you will reference that module and items:

use mnemonic::ItemInMnemonic; // Make sure this is `pub`!
mod mnemonic;

Using a nested module mnemonic from the crate mnemonic in other crates

Export the module from your crate, and then reference it from other crates:

// src/lib.rs
pub mod mnemonic; // Note the module is now public

// In the crate that consumes mnemonic
extern crate mnemonic;
use mnemonic::mnemonic::ItemInMnemonic;

This last option is kind of ugly though, you probably don't want to make your users type mnemonic::mnemonic, which is why I suggest just putting it in src/lib.rs.

Upvotes: 3

Related Questions