柚子快報(bào)激活碼778899分享:開(kāi)發(fā)語(yǔ)言 Rust的模塊化
柚子快報(bào)激活碼778899分享:開(kāi)發(fā)語(yǔ)言 Rust的模塊化
Rust的模塊化要從Rust的入口文件談起。
Rust的程序的入口文件有兩個(gè)
如果程序類(lèi)型是可執(zhí)行應(yīng)用,入口文件是main.rs;如果程序類(lèi)型是庫(kù),入口文件是lib.rs;
入口文件中,必須聲明本地模塊,否則編譯器在編譯過(guò)程中,會(huì)報(bào)該模塊不存在的錯(cuò)誤。這個(gè)規(guī)則,在其它程序的編譯中很少見(jiàn)。
怎么理解這個(gè)規(guī)則,我來(lái)舉一個(gè)例子: 假設(shè)我們目錄結(jié)構(gòu)如下:
src/
components/
mod.rs
table_component.rs
models/
mod.rs
table_row.rs
main.rs
依賴關(guān)系如下,即main.rs沒(méi)有直接依賴table_row.rs
main.rs -> table_component.rs -> table_row.rs
現(xiàn)在來(lái)看看模塊之間的引用代碼。 main.rs對(duì)table_component.rs的依賴,對(duì)應(yīng)的代碼為
use components::table_component::TableComponent;
table_component.rs對(duì)table_row.rs的依賴,對(duì)應(yīng)的代碼為
use crate::models::table_row::TableRow;
上面的依賴代碼都沒(méi)毛病。在main.rs中"use components::table_component::TableComponent"這段代碼告訴編譯器,從模塊的根部找components模塊,因?yàn)閏omponents是一個(gè)文件夾,所以components目錄下有一個(gè)mod.rs,然后在components文件夾下找table_component模塊,最后在table_component模塊中找到TableComponent。
因?yàn)閠able_component.rs中使用到了models中定義的TableRow,所以,這行代碼也沒(méi)有毛?。骸皍se crate::models::table_row::TableRow"。這行代碼告訴編譯器從模塊的根目錄找models模塊,然后在models模塊中找table_row模塊,最后在table_row中找到TableRow。
但是如果僅僅是這樣,編譯器就會(huì)馬上送上模塊找不到的錯(cuò)誤。這種錯(cuò)誤對(duì)于才接觸到Rust的同學(xué)來(lái)說(shuō),可能很難發(fā)現(xiàn),尤其是才從別的開(kāi)發(fā)語(yǔ)言(比如Javascript)過(guò)來(lái)的同學(xué)。
--> src/main.rs:4:5
use components::table_component::TableComponent;
^^^^^^^^^^ use of undeclared crate or module `components`
上面的錯(cuò)誤里中有“undclared crate or module",這里其實(shí)就是在提醒我們這個(gè)components模塊沒(méi)有被聲明。 很簡(jiǎn)單,就是在main.rs的頭部加上下面的代碼。
mod components;
OK,如果你再次編譯代碼,你會(huì)發(fā)現(xiàn)下面這個(gè)錯(cuò)誤。
--> src/components/table_component.rs:1:12
use crate::models::table_row::TableRow;
^^^^^^ could not find `models` in the crate root
如果沒(méi)有把模塊聲明的原則放心上,這個(gè)提示會(huì)讓人發(fā)狂,因?yàn)闊o(wú)論你檢查多少次,你都會(huì)發(fā)現(xiàn)你的文件路徑src/models/table_row.rs和模塊的查找路徑是對(duì)應(yīng)的啊,為什么就找不到呢?
如果這里的報(bào)錯(cuò)還是能像之前那樣用“use of undeclared crate or module"就好理解多了。要解決這個(gè)問(wèn)題,其實(shí)也是將"mod models;"這行代碼添加到main.rs中。即: main.rs
mod components;
mod models;
把握好這個(gè)原則,其它模塊間的引用方式,例如super, self都好理解了。
柚子快報(bào)激活碼778899分享:開(kāi)發(fā)語(yǔ)言 Rust的模塊化
好文閱讀
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。