I'm trying to create a module in Rust and then use it from a different file. This is my file structure:
matthias@X1:~/projects/bitter-oyster$ tree
.
├── Cargo.lock
├── Cargo.toml
├── Readme.md
├── src
│ ├── liblib.rlib
│ ├── lib.rs
│ ├── main.rs
│ ├── main.rs~
│ └── plot
│ ├── line.rs
│ └── mod.rs
└── target
└── debug
├── bitter_oyster.d
├── build
├── deps
├── examples
├── libbitter_oyster.rlib
└── native
8 directories, 11 files
This is Cargo.toml:
[package]
name = "bitter-oyster"
version = "0.1.0"
authors = ["matthias"]
[dependencies]
This is main.rs:
extern crate plot;
fn main() {
println!("----");
plot::line::test();
}
This is lib.rs:
mod plot;
this is plot/mod.rs
mod line;
and this is plot/line.rs
pub fn test(){
println!("Here line");
}
When I try to compile my program using: cargo run
I get:
Compiling bitter-oyster v0.1.0 (file:///home/matthias/projects/bitter-oyster)
/home/matthias/projects/bitter-oyster/src/main.rs:1:1: 1:19 error: can't find crate for `plot` [E0463]
/home/matthias/projects/bitter-oyster/src/main.rs:1 extern crate plot;
How do I compile my program? As far as I can tell from online documentations this should work, but it doesn't.
To add to the given answers, a library compiled as a
cdylib
(docs) can generate this error when you try to reference it in another project. I solved it by separating the code I wished to reuse in a regularlib
project.If you see this error:
it could be that you haven't added the desired crate to the dependencies list in your
Cargo.toml
:See specifying dependencies in the Cargo docs.
You have the following problems:
you have to use
extern crate bitter_oyster;
inmain.rs
, because the produced binary uses your crate, the binary is not a part of it.Also, call
bitter_oyster::plot::line::test();
inmain.rs
instead ofplot::line::test();
.plot
is a module in thebitter_oyster
crate, such asline
. You are referring to thetest
function with its fully qualified name.Make sure, that every module is exported in the fully qualified name. You can make a module public with the
pub
keyword, likepub mod plot;
You can find more information about Rust's module system here: https://doc.rust-lang.org/book/crates-and-modules.html
A working copy of your module structure is as follows:
src/main.rs:
src/lib.rs:
src/plot/mod.rs:
src/plot/line.rs :