Overview
Symbol is a short string type with a limited character set, used for symbolic identifiers such as function names and user-defined structure field/enum variant names.
Characteristics:
- Valid characters:
a-zA-Z0-9_ - Maximum length: 32 characters
- Symbols ≤ 9 characters are more efficient at runtime
- Short symbols (≤ 9 chars) can be computed at compile time
Creating Symbols
new()
Creates a new Symbol from a string with valid characters.
symbol_short!() Macro
For short symbols (≤ 9 characters), use the symbol_short!() macro to ensure compile-time conversion:
The
symbol_short!() macro ensures the conversion always occurs at compile time, avoiding runtime overhead in the Wasm binary.short() (Deprecated)
Creates a short symbol (≤ 9 characters). This method is deprecated in favor of symbol_short!().
Comparison
Symbols support full comparison operations:Conversion Methods
as_val() / to_val()
Convert to Val representation.
to_symbol_val()
Convert to SymbolVal representation.
to_string() (Non-Wasm only)
Convert the Symbol to a Rust String.
Traits
Symbol implements:
CloneDebugEq,PartialEqOrd,PartialOrdTryFromVal<Env, &str>
Examples
Function Names
Dynamic Symbol Creation
Symbol as Map Key
Compile-Time Short Symbols
Best Practices
- Use
symbol_short!()for symbols ≤ 9 characters: This ensures compile-time evaluation and smaller Wasm binaries.
- Use
Symbol::new()for longer symbols or dynamic creation:
-
Stick to alphanumeric and underscore characters: Only
a-zA-Z0-9_are valid. - Keep symbols short: While 32 characters are allowed, shorter symbols are more efficient.