Constants
Constants are a way of giving a name to shared, static values inside of a module
or script
.
The constant's must be known at compilation. The constant's value is stored in the compiled module or script. And each time the constant is used, a new copy of that value is made.
Declaration​
Constant declarations begin with the const
keyword, followed by a name, a type, and a value. They
can exist in either a script or module
const <name>: <type> = <expression>;
For example
script {
const MY_ERROR_CODE: u64 = 0;
fun main(input: u64) {
assert!(input > 0, MY_ERROR_CODE);
}
}
address 0x42 {
module example {
const MY_ADDRESS: address = @0x42;
public fun permissioned(s: &signer) {
assert!(std::signer::address_of(s) == MY_ADDRESS, 0);
}
}
}
Naming​
Constants must start with a capital letter A
to Z
. After the first letter, constant names can
contain underscores _
, letters a
to z
, letters A
to Z
, or digits 0
to 9
.
const FLAG: bool = false;
const MY_ERROR_CODE: u64 = 0;
const ADDRESS_42: address = @0x42;
Even though you can use letters a
to z
in a constant. The
general style guidelines are to use just uppercase letters A
to Z
,
with underscores _
between each word.
This naming restriction of starting with A
to Z
is in place to give room for future language
features. It may or may not be removed later.
Visibility​
public
constants are not currently supported. const
values can be used only in the declaring
module.
Valid Expressions​
Currently, constants are limited to the primitive types bool
, u8
, u16
, u32
, u64
, u128
, u256
, address
, and
vector<u8>
. Future support for other vector
values (besides the "string"-style literals) will
come later.