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

  • Mastering Rust
  • Rahul Sharma Vesa Kaihlavirta
  • 278字
  • 2021-07-02 13:35:17

Modules, imports, and use statements

Languages often provide a way to split large code bases into multiple files to manage complexity. Java follows the convention of a single public class per .java file, while C++ provides us with header files and include statements. Rust is no different and provides us with modules. Modules are a way to namespace or organize code in a Rust program. To allow flexibility in organizing our code, there are multiple ways to create modules. Modules are a complex topic to understand and to make it brief for this section, we'll highlight only the important aspects about using them. Modules are covered in detail in Chapter 2, Managing Projects with Cargo. The following are the key takeaways about modules in Rust:

  • Every Rust program needs to have a root module. In executables, it is usually the main.rs file, and for libraries, it is lib.rs.
  • Modules can be declared within other modules or can be organized as files and directories.
  • To let the compiler know about our module, we need to declare it using the mod keyword, as in mod my_module;, in our root module.
  • To use any of the items within the module, we need to use the use keyword, along with the name of the module. This is known as bringing the item into scope.
  • Items defined within modules are private by default, and you need to use the pub keyword to expose them to their consumers.

That was modules in brief. Some of the advanced aspects of modules are also covered in Chapter 7, Advanced Concepts. Next, let's look at the commonly used collection types that are available in the standard library.

主站蜘蛛池模板: 清远市| 通渭县| 新巴尔虎左旗| 衢州市| 冀州市| 巴里| 南宁市| 长乐市| 普洱| 邹城市| 公安县| 内丘县| 蛟河市| 巴南区| 宣化县| 阿巴嘎旗| 犍为县| 库尔勒市| 宁陵县| 秦安县| 神池县| 南平市| 和平县| 永胜县| 青神县| 新源县| 专栏| 宾川县| 博客| 吉林省| 东至县| 宿松县| 灌云县| 西乌珠穆沁旗| 句容市| 馆陶县| 康平县| 南涧| 罗江县| 崇阳县| 犍为县|