常量 #
常量是一种为模块或脚本内的共享静态值命名的方法。在 Move 中,常量是使用 const 关键字声明的。
常量必须在编译时已知。 常量的值存储在已编译的模块或脚本中。 每次使用常量时,都会制作该值的新副本。 句法:
语法:
const <NAME>: <TYPE> = <EXPRESSION>;
module my_addrx::Constants
{
use std::debug::print;
//Some Examples
const X:u64=10;
const Y:address=@my_addrx;
const Z:bool=false;
fun constants()
{
print(&X);
print(&Y);
print(&Z);
}
#[test]
fun testing()
{
constants();
}
}
命名:
常量必须以大写字母 A 到 Z 开头。在第一个字母之后,常量名称可以包含下划线 _、字母 a 到 z、字母 A 到 Z 或数字 0 到 9。
//Valid
const Foo:u64=123;
const Flag:bool=true;
const My_Addrx:address=@my_addrx;
//Invalid;
const x:u8=10;
const flag:bool=false;
const my_addrx:address=@my_addrx;
其他一些要点:
- 常量仅限于基本类型
bool、u8、u16、u32、u64、u128、u256、address和vector<u8>。 - 如果常量名称表示错误代码(例如,
EIndexOutOfBounds),则常量名称应为大写驼峰式并以E开头;如果它们表示非错误值(例如,MIN_STAKE),则应为大写蛇形。 - 当前不支持
public(公共)常量。const值只能在声明模块中使用。 - 无法在其模块或脚本范围之外访问常量值。