[英]How to include files from same directory in a module using Cargo/Rust?
[英]How to use one module from another module in a Rust cargo project?
有很多關於使用模塊的 Rust文檔,但我還沒有找到具有多個模塊的 Cargo 二進制文件的示例,其中一個模塊使用另一個模塊。 我的示例在 src 文件夾中包含三個文件。 模塊 a 和 b 處於同一級別。 一個不是另一個的子模塊。
主.rs:
mod a;
fn main() {
println!("Hello, world!");
a::a();
}
答:
pub fn a() {
println!("A");
b::b();
}
和 b.rs:
pub fn b() {
println!("B");
}
我在 a.rs 中嘗試了use b
和mod b
的變體,但我無法編譯此代碼。 例如,如果我嘗試使用use b
,我會收到以下錯誤:
--> src/a.rs:1:5
|
1 | use b;
| ^ no `b` in the root. Did you mean to use `a`?
讓 Rust 認識到我想在貨物應用程序中使用模塊 a 中的模塊 b 的正確方法是什么?
您必須在某處包含b.rs
,通常使用mod b;
. 如果b
是一個孩子a
(而不是被的兄弟a
),有兩種方法可以做到這一點:
a.rs
到a/mod.rs
和b.rs
到a/b.rs
。 然后你可以修改mod b;
在a/mod.rs
。#[path = "b.rs"] mod b;
在a.rs
無需重命名源。 如果b
旨在成為的兄弟a
(而不是被一個孩子a
),你可以mod b;
在main.rs
,然后use crate::b;
在a.rs
接受的答案中的方法在 Rust 1.33 中對我不起作用。 相反,我像這樣使用兄弟模塊:
use crate::b;
在最新的 Rust 1.63 中,我們可以使用super關鍵字來引用兄弟姐妹
// main.rs
mod a;
mod b;
fn main() {
}
// a.rs
pub fn a() {
println!("A");
super::b::b();
}
// b.rs
pub fn b() {
println!("B");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.