官术网_书友最值得收藏!

  • Rust Quick Start Guide
  • Daniel Arbuckle
  • 218字
  • 2021-06-10 19:46:03

A module as a separate file

More often than not, we're going to want to give our modules their own files. It's just nicer to keep things separated and contained as much as possible, because it helps keep the code manageable. Fortunately, this is just as easy. In our .rs file, we can just write something like the following:

pub mod module_b;

That looks a lot like the previous example, except that it doesn't have the module contents right there between { and }. Instead, the Rust compiler goes looking for a file called either module_b.rs or module_b/mod.rs, and uses the whole file as the contents of the module_b module. So, if the file contains a couple of functions similar to the ones we saw previously:

pub fn a_thing() {
println!("This is a module_b thing");
}

pub fn a_second_thing() {
a_thing();
println!("This is another module_b thing");
}

Then module_b will contain two functions named a_thing and a_second_thing. It's not a problem that those functions have the same names as functions in the module_a module from before, because they're in a different module.

Why did the compiler look in two places for the source code of module_b? This allows us to be more flexible in how we lay out our directory structure for our program's source code.
主站蜘蛛池模板: 蛟河市| 西贡区| 嫩江县| 安仁县| 宜兰县| 翁牛特旗| 清原| 安达市| 会泽县| 合川市| 常德市| 竹北市| 二连浩特市| 闽侯县| 平阳县| 衡山县| 合阳县| 周口市| 长春市| 寿宁县| 贵德县| 高邑县| 株洲县| 石嘴山市| 青神县| 都昌县| 神农架林区| 颍上县| 新乡市| 延庆县| 栾城县| 平潭县| 大港区| 千阳县| 康平县| 吴江市| 泉州市| 安顺市| 潢川县| 平乐县| 万荣县|