常數 (Constants)
常數是在模組層級定義的不可變值。它們通常用來為整個模組中使用的靜態值命名。例如,若產品有預設價格,你可能會為其定義常數。常數儲存在模組的位元組碼中,每次使用時都會複製其值。如同每個模組成員,常數預設為私有;但與函式或結構不同的是,它們無法設為公開。下方的設定模式說明如何在模組之間共用它們。
module book::shop_price;
use sui::{coin::Coin, sui::SUI};
/// Trying to purchase an item at an incorrect price.
const EWrongPrice: u64 = 0;
/// The price of an item in the shop.
const ITEM_PRICE: u64 = 100;
/// The owner of the shop, an address.
const SHOP_OWNER: address = @0xa11ce;
/// An item sold in the shop.
public struct Item {}
/// Purchase an item from the shop.
public fun purchase(coin: Coin<SUI>): Item {
assert!(coin.value() == ITEM_PRICE, EWrongPrice);
transfer::public_transfer(coin, SHOP_OWNER);
Item {}
}
命名慣例 (Naming Convention)
常數必須以大寫字母開頭,這會在編譯器層級強制執行。對於作為值使用的常數,慣例是全部使用大寫字母,並以底線分隔單字,讓常數在原始碼中與其他識別字有所區別。錯誤常數是例外,它們會以 E 開頭,後接 CamelCase 描述,例如 ENoAccess。
/// Price of the item used at the shop.
const ITEM_PRICE: u64 = 100;
/// Error constant.
const EItemNotFound: u64 = 1;
常數不可變 (Constants Are Immutable)
常數無法變更或指派新值。作為套件位元組碼的一部分,它們本質上不可變。
module book::immutable_constants;
const ITEM_PRICE: u64 = 100;
// 產生錯誤
fun change_price() {
ITEM_PRICE = 200;
}
使用設定模式 (Using the Config Pattern)
應用程式常見的使用情境是定義一組在整個原始碼庫中使用的常數。但由於常數對模組而言是私有的,其他模組無法存取它們。解決方法之一是定義一個「設定」模組,透過公開函式匯出常數:
module book::config;
const ITEM_PRICE: u64 = 100;
const TAX_RATE: u64 = 10;
const SHIPPING_COST: u64 = 5;
/// Returns the price of an item.
public fun item_price(): u64 { ITEM_PRICE }
/// Returns the tax rate.
public fun tax_rate(): u64 { TAX_RATE }
/// Returns the shipping cost.
public fun shipping_cost(): u64 { SHIPPING_COST }
如此一來,其他模組便能匯入並讀取這些常數,且更新流程也會簡化。若需要變更常數,只需在套件升級時更新設定模組。
延伸閱讀 (Further Reading)
- Move 參考資料中的常數
- 常數的程式碼撰寫慣例