从接触Rust到现在一年多了,目前还是没有找到门,看之前写的自学笔记,可读性几乎为零。现在这篇尽量用“人话”记录一下我对Rust项目组织结构的理解。
首先是 package 和 crate 之间的关系。
Package 里可以有一个或者多个 crate(但是不能没有),这些crate 中最多有一个 library crate(也可以没有),binary crate个数不限(如果没有 library crate,可想而知必须至少得有个binary crate;如果有 library crate,可能没有 binary crate,有点绕……)。
A crate will group related functionality together in a scope so the functionality is easy to share between multiple projects.
Crate 主要集成功能。
Modules let us organize code within a crate into groups for readability and easy reuse. Modules also control the privacy of items, which is whether an item can be used by outside code (public) or is an internal implementation detail and not available for outside use (private).
Module 增加代码可读性、复用性,以及隐私性。
绝对路径和相对路径均可, 绝对路径更具普遍性,具体情况具体分析。
使用
use
和
as
,以及
mod mod_name;
来拆分module为多文件。
有一个实操
网站
。
Rust automagically looks for it inside the file, if doesn’t find it, looks for a file with the module name in the same folder (in this case
src/
) and if still doesn’t find it looks for a folder with the module name and a file mod.rs inside, there it looks for the code.