Skip to main content

模組 (Module)

模組是 Move 中組織原始碼的基本單位。模組用於將原始碼分組及隔離,而且模組的所有成員預設皆為模組私有。這使模組成為信任邊界:如後續章節所示,只有定義型別的模組可以建立、修改及銷毀其值。本節將說明如何定義模組、宣告其成員,以及從其他模組存取它。

模組宣告 (Module Declaration)​

模組使用 module 關鍵字宣告,後接以 :: 分隔的套件地址與模組名稱,接著是分號及模組主體。模組名稱應採用 snake_case 格式——全部使用小寫字母,並以底線分隔單字。模組名稱在套件中必須是唯一的。

通常,sources/ 資料夾中的單一文件會包含單一模組。檔案名稱應與模組名稱相符——例如,donut_shop 模組應儲存在 donut_shop.move 檔案中。你可以在程式碼撰寫慣例章節中進一步閱讀程式碼撰寫慣例。

若需要在一個檔案中宣告多個模組,必須使用模組區塊語法。

// Module label.
module book::my_module;

// module body

地址與具名地址 (Address and Named Address)​

模組地址可透過兩種方式指定:作為地址字面值(不需要 @ 前綴),或作為在套件清單中宣告的套件名稱。

module 0x0::address_literal { /* ... */ }
module book::named_address { /* ... */ }

Move.toml 中的套件區段:

[package]
name = "book"
edition = "2024"

模組成員 (Module Members)​

模組成員在模組主體內宣告。為了說明這點,讓我們定義一個簡單的模組,其中包含匯入、常數、結構及函式:

module book::my_module_with_members;

// import - brings the `my_module` module into scope
use book::my_module;

// a constant - an immutable, module-private value
const CONST: u8 = 0;

// a struct - a custom data type
public struct Struct {}

// a function - a unit of executable code
fun function() { /* function body */ }

每個成員都以各自的關鍵字開頭:use 將其他模組帶入作用域(匯入模組)、const 定義永不變更的值(常數)、struct 宣告自訂資料型別(結構),而 fun 宣告函式(函式)。暫時不必擔心細節——本章會為每一項提供專屬章節;目前只要能辨識這些關鍵字,並知道它們全都位於模組層級即可。

模組區塊 (Module Block)​

Move 的 2024 版以前版本要求模組主體必須是模組區塊——以大括號 {} 包圍的模組內容。區塊語法仍受支援,而相較於上述的標籤語法,唯一偏好使用它的理由是在一個檔案中宣告多個模組——這很少需要,也不是建議的做法。

module book::my_block_module_with_members {
// import
use book::my_module;

// a constant
const CONST: u8 = 0;

// a struct
public struct Struct {}

// method alias
public use fun function as Struct.struct_fun;

// function
fun function(_: &Struct) { /* function body */ }
}

// module block allows multiple module definitions in the
// same file but this is not a recommended practice
module book::another_module_in_the_file {
// ...
}

延伸閱讀 (Further Reading)​

  • Move 參考文件中的模組。