Constants
Constants are immutable values known at compile time.
Declaration
Section titled “Declaration”const MAX_CONNECTIONS = 1000const APP_VERSION = "1.4.0"const DEBUG_MODE = falseConstant Expressions
Section titled “Constant Expressions”Constants can be assigned from constant expressions:
const BASE_URL = "https://api.example.com"const API_PATH = "/v1"const FULL_URL = BASE_URL + API_PATHType Annotations
Section titled “Type Annotations”Type annotations are optional but recommended for clarity:
const TIMEOUT: Int = 30const MAX_RETRIES: Int = 3const DEFAULT_NAME: String = "anonymous"Module-Level Constants
Section titled “Module-Level Constants”Constants are typically declared at the module level:
const PI = 3.14159265358979const E = 2.71828182845905
action circle_area(@radius: Float) -> Float return PI * @radius * @radiusfin action.Scoped Constants
Section titled “Scoped Constants”Constants can be defined inside actions:
action process() const LOCAL_LIMIT = 50 for @i in 0..LOCAL_LIMIT process_item(@i) fin for.fin action.Enum Constants
Section titled “Enum Constants”Enums define a set of named constants:
enum Color Red Green Bluefin enum.
@// Usage@primary = Color#RedSee Enums for full details.
Constant vs Variable
Section titled “Constant vs Variable”| Feature | Variable (@) |
Constant (const) |
|---|---|---|
| Mutability | Mutable with mut |
Always immutable |
| Assignment | Runtime | Compile time |
| Scope | Block or module | Block or module |
| Type inference | Yes | Yes |
| Shadowing | Yes | No |
Naming Convention
Section titled “Naming Convention”Constants use CONSTANT_CASE (uppercase with underscores):
const MAX_BUFFER_SIZE = 8192const DEFAULT_TIMEOUT_MS = 5000const ENABLE_LOGGING = trueImporting Constants
Section titled “Importing Constants”Constants can be imported from other modules:
import { MAX_RETRIES, API_KEY } from config
action connect() for @i in 0..MAX_RETRIES if try_connect() return true fin if. fin for. return falsefin action.Compile-Time Evaluation
Section titled “Compile-Time Evaluation”Constants are evaluated at compile time, enabling optimizations:
const SIZE = 1024 * 1024 @// Computed at compile timeconst FLAGS = 0x01 | 0x02 @// Bitwise operations allowedExpressions in constants must be determinable at compile time. Function calls are not allowed unless they are const functions (future feature).
Next Steps
Section titled “Next Steps”Learn about Types to understand Draft’s type system.
