我正在尝试在Rust中创建一个模块,然后从另一个文件中使用它.这是我的文件结构:
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
Run Code Online (Sandbox Code Playgroud)
这是Cargo.toml:
[package]
name = "bitter-oyster"
version = "0.1.0"
authors = ["matthias"]
[dependencies]
Run Code Online (Sandbox Code Playgroud)
这是主要的:
extern crate plot;
fn main() {
println!("----");
plot::line::test();
}
Run Code Online (Sandbox Code Playgroud)
这是lib.rs:
mod plot;
Run Code Online (Sandbox Code Playgroud)
这是情节/模型
mod line;
Run Code Online (Sandbox Code Playgroud)
这是plot/line.rs
pub fn test(){
println!("Here line");
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用以下方法编译程序时:cargo run我得到:
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;
Run Code Online (Sandbox Code Playgroud)
我如何编译我的程序?据我可以从在线文档中看出这应该有效,但事实并非如此.
Tib*_*nke 17
您有以下问题:
你必须使用extern crate bitter_oyster;in main.rs,因为生成的二进制文件使用你的crate,二进制文件不是它的一部分.
此外,呼叫bitter_oyster::plot::line::test();中main.rs代替plot::line::test();.plot是bitter_oyster箱子里的一个模块,比如line.您指的是test具有完全限定名称的函数.
确保每个模块都以完全限定名称导出.您可以使用pub关键字公开模块,例如pub mod plot;
您可以在此处找到有关Rust模块系统的更多信息:https://doc.rust-lang.org/book/crates-and-modules.html
模块结构的工作副本如下:
SRC/main.rs:
extern crate bitter_oyster;
fn main() {
println!("----");
bitter_oyster::plot::line::test();
}
Run Code Online (Sandbox Code Playgroud)
SRC/lib.rs:
pub mod plot;
Run Code Online (Sandbox Code Playgroud)
SRC /剧情/ mod.rs:
pub mod line;
Run Code Online (Sandbox Code Playgroud)
src/plot/line.rs:
pub fn test(){
println!("Here line");
}
Run Code Online (Sandbox Code Playgroud)
And*_*den 14
如果您看到此错误:
error[E0463]: can't find crate for `PACKAGE`
|
1 | extern crate PACKAGE;
| ^^^^^^^^^^^^^^^^^^^^^ can't find crate
Run Code Online (Sandbox Code Playgroud)
可能是您没有将所需的包添加到您的依赖项列表中Cargo.toml:
[dependencies]
PACKAGE = "1.2.3"
Run Code Online (Sandbox Code Playgroud)
请参阅在Cargo文档中指定依赖项.