簡體   English   中英

如何在 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 bmod 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.rsa/mod.rsb.rsa/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM