【问题标题】:Include main.rs in other module在其他模块中包含 main.rs
【发布时间】:2020-04-16 07:35:17
【问题描述】:

我是生锈的新手。我知道,为了调用同一文件夹中的模块,我需要为其他文件夹 mod <module name>{ include!("path to module") } 编写 mod <module name>。我想将main.rs 包含在extra.rs 中,存在于同一文件夹中,以便我可以在extra.rs 中使用Summary 结构feed 特征。我收到错误recursion limit reached while expanding the macro 'include'。 如何在extra.rs 中包含main.rs?有没有更好的方法来编写相同的代码?

错误

error: recursion limit reached while expanding the macro `include`
 --> src/extra.rs:3:5
  |
3 |     include!("main.rs");
  |     ^^^^^^^^^^^^^^^^^^^^
  |
  = help: consider adding a `#![recursion_limit="256"]` attribute to your crate

error: aborting due to previous error

error: could not compile `office_manager`.

main.rs

mod extra;

pub trait Summary {
    fn print_summry(&self) -> String;
}

pub struct Tweet {
    name: String,
    message: String
}

impl Summary for Tweet {
    fn print_summry(&self) -> String {
        format!("{}: {}",self.name,self.message)
    }
}

fn main() {

    let t = extra::Feed {
        name: String::from("Hanuman"),
        message: String::from("Jai sri Ram")
    };

    println!("{}",t.print_summry());

}

extra.rs

mod main {
    include!("main.rs");
}


pub struct Feed {
    pub name: String,
    pub message: String
}

impl Summary for Feed {
    fn print_summry(&self) -> String {
        format!("{}: {}",self.name,self.message)
    }
}

【问题讨论】:

  • Rust 不是 C,你很可能不想使用include!,只需在extra.rs 的顶部添加use super::*;
  • 实际上,(ab)使用use super::*; 也不是一个好主意,因为它会将所有内容都纳入范围。只需使用use super::Summary; 导入您需要的内容。 super 关键字引用当前一个的父 module(在这种情况下 - main.rs)。

标签: rust rust-cargo


【解决方案1】:

可以在super 的帮助下访问父模块的元素。因此在顶部添加use super::*; 或使用super::Summary 都可以。但最好使用super::Summary,因为它不包含main.rs 的所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-09-22
    • 2016-03-29
    • 2017-01-21
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多