简体   繁体   English

如何在除 main.rs 之外的另一个文件中使用模块

[英]How to use module in another file besides main.rs

I have 3 files in my src folder: 'main.rs', 'network.rs', and 'nodes.rs'.我的 src 文件夹中有 3 个文件:“main.rs”、“network.rs”和“nodes.rs”。 I would like to use a function I declared in nodes.rs in network.rs.我想使用我在network.rs 中的nodes.rs 中声明的函数。 I cannot seem to find a way to do this.我似乎找不到办法做到这一点。 All I can find online are ways to access the functions within main.rs.我在网上只能找到访问 main.rs 中的功能的方法。

main.rs: main.rs:

mod network;
mod nodes;

fn main() {
    network::run();
}

network.rs网络.rs

pub fn run() {
    newnode();
}

nodes.rs节点.rs

pub fn newnode() {
    println!("Test");
}

If you don't want to call the functions with the full path, you need to explicitly refer to them in the appropriate module with use .如果您不想使用完整路径调用函数,则需要在适当的模块中use显式引用它们。

At the beginning of network.rs : use super::nodes::newnode;network.rs开头: use super::nodes::newnode; . .

To access the nodes modules, you need to navigate back to main.rs and then descend to the submodule.要访问nodes模块,您需要导航回main.rs ,然后下降到子模块。 You can do that by either starting from the root of the crate ( main.rs in this example) with the crate keyword (so crate::nodes::newnode ), or, because main.rs is the parent module of network , accessing it via super : super::nodes::newnode .您可以通过使用crate关键字(因此crate::nodes::newnode )从 crate 的根(本例中为main.rs )开始,或者因为main.rsnetwork的父模块,访问它通过super : super::nodes::newnode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM