const
A named, immutable value declared at module scope.
const max_tracks: uint16 = 512;
const home_station: string = "GroundStation-1";Declaration
A const is a name, a type, and an initializer, and both the type and the initializer are mandatory.
A value bound inside a block is a let instead.
- Omitting the type or the initializer is a parse error, so neither
const max_tracks = 512;norconst max_tracks: uint16;parses. - The name is unique among the file's declarations.
- The initializer must be assignable to the declared type, and a numeric literal in it pins to that type.
- A const is a global declaration, so another module imports it the way it imports a type.
- Annotations precede the declaration.
annotation Units(name: string)
@Units("meters")
const max_range_m: float32 = 250000.0;Initializers
The initializer is an expression, not only a literal: arithmetic, a struct literal, an enum member, a call to a function the file declares.
- A const may reference another const. Declaration order does not matter, so the reference may name a const declared further down the file.
- A reference carries the const's declared type, so arithmetic on it is that type's arithmetic, wrapping included.
- A const of a struct type is constructed the way any other value of that type is, so the struct's
assertions run and a failing one is catchable with
try. - A const is in scope wherever a value expression is: a function body, a struct assertion, a
sendpredicate.
struct SearchSector {
start_deg: uint16;
end_deg: uint16;
assert ordered = start_deg < end_deg;
}
enum TrackKind int32 { Air = 0; Surface = 1; }
const max_tracks: uint16 = 512;
const half_tracks: uint16 = max_tracks / 2;
const default_kind: TrackKind = TrackKind.Air;
const forward: SearchSector = SearchSector { start_deg = 350; end_deg = 360; };
const reversed: SearchSector = SearchSector { start_deg = 90; end_deg = 10; };
half_tracks // => 256
max_tracks * 128 // => 0
default_kind // => TrackKind.Air
forward.end_deg // => 360
try(reversed) // => noneErrors
An initializer that does not match the declared type
const tracking_enabled: bit = "true"; // error: type-mismatchA const that references itself
const max_tracks: uint16 = max_tracks + 1; // error: const-self-referenceConsts that reference each other
A cycle is rejected however many consts it runs through, and every const on it is reported.
const max_tracks: uint16 = max_sectors; // error: cyclic-const
const max_sectors: uint16 = max_tracks; // error: cyclic-constNaming a const where a type is expected
A const binds a value and never introduces a type.
const max_tracks: uint16 = 512;
struct TrackTable {
entries: max_tracks; // error: not-a-type
}Related
- struct — declaring a type a const can hold.