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

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.
主站蜘蛛池模板: 武威市| 遵义县| 沧州市| 合作市| 锡林浩特市| 溆浦县| 永顺县| 济源市| 龙里县| 凤山县| 乐山市| 海门市| 淳化县| 镶黄旗| 徐水县| 西吉县| 革吉县| 高青县| 交城县| 阳城县| 蓝田县| 正阳县| 冀州市| 阿克陶县| 连平县| 凤山市| 京山县| 景洪市| 驻马店市| 徐汇区| 渭源县| 磐安县| 木里| 永福县| 佛坪县| 昆山市| 成武县| 双流县| 聂拉木县| 会宁县| 南和县|