Literals
Literals are fixed values written directly in source code. Cambrian supports numeric literals in several bases, string and byte literals, booleans, collection constructors, and optional values.
Numeric Literals
Decimal
Plain decimal integers are the most common form:
let count = 42;
let large = 1000000;
Underscore Separators
Underscores can appear anywhere within a numeric literal to improve readability. They are ignored by the compiler:
let million = 1_000_000;
let fee = 100_000;
let precise = 1_234_567_890;
Hexadecimal
Hexadecimal literals start with 0x or 0X:
let flags = 0xFF;
let mask = 0xDEAD_BEEF;
Binary
Binary literals start with 0b or 0B:
let bits = 0b101010;
let byte_val = 0b1111_0000;
String Literals
String literals are enclosed in double quotes and produce String values:
let greeting = "hello";
let name = "Cambrian";
let empty_str = "";
Standard escape sequences are supported within string literals.
Byte Literals
Byte literals are prefixed with b and produce bytes values:
let raw = b"raw data";
let payload = b"message body";
Byte literals are useful when working with raw binary data that should not be interpreted as UTF-8 text.
Boolean Literals
The two boolean values:
let active = true;
let paused = false;
Collection Literals
Empty HashMap
An empty HashMap is written with empty braces:
let scores: HashMap<address, u64> = {};
Vec (Array)
Vectors are created with the array function. It accepts zero or more
comma-separated values:
let empty: Vec<u64> = array();
let nums = array(1, 2, 3);
let addrs = array(addr1, addr2);
Optional Literals
The Option<T> type has two constructors:
some
Wraps a value in Option:
let found = some(42);
let user = some(msg::sender);
none
Represents the absence of a value:
let missing: Option<u64> = none;
Record Literals
Records are constructed by specifying values for all fields:
record Transaction {
id: u64,
value: U256,
sender: address
}
let tx = Transaction {
id: 1,
value: 100,
sender: msg::sender
};
See Records for full details on record construction and functional update syntax.
Summary
| Literal Form | Type | Example |
|---|---|---|
| Decimal | Integer | 42, 1_000 |
| Hexadecimal | Integer | 0xFF, 0xDEAD |
| Binary | Integer | 0b101010 |
| Double-quoted string | String | "hello" |
| Byte string | bytes | b"raw" |
| Boolean | bool | true, false |
| Empty braces | HashMap<K,V> | {} |
array(...) | Vec<T> | array(1, 2, 3) |
some(value) | Option<T> | some(42) |
none | Option<T> | none |
| Record constructor | Record type | Foo { x: 1 } |