Var statement
Var statements declare new local and global variables and initialize them. A comma-separated list of variables can be used to specify variables of the same type:
var
a: int = 0
x, y, z: int
If an initializer is given, the type can be omitted: the variable is then of the same type as the initializing expression. Variables are always initialized with a default value if there is no initializing expression. The default value depends on the type and is always a zero in binary.
Type | default value |
---|---|
any integer type | 0 |
any float | 0.0 |
char | ‘\0’ |
bool | false |
ref or pointer type | nil |
procedural type | nil |
sequence | @[] |
string | “” |
tuple[x: A, y: B, …] | (zeroDefault(A), zeroDefault(B), …) (analogous for objects) |
array[0…, T] | [zeroDefault(T), …] |
range[T] | default(T); this may be out of the valid range |
T = enum | castT; this may be an invalid value |
The implicit initialization can be avoided for optimization reasons with the noinit pragma:
var
a {.noinit.}: array[0..1023, char]
If a proc is annotated with the noinit pragma, this refers to its implicit result variable:
proc returnUndefinedValue: int {.noinit.} = discard
The implicit initialization can also be prevented by the requiresInit type pragma. The compiler requires an explicit initialization for the object and all of its fields. However, it does a control flow analysis to prove the variable has been initialized and does not rely on syntactic properties:
type
MyObject {.requiresInit.} = object
proc p() =
# the following is valid:
var x: MyObject
if someCondition():
x = a()
else:
x = a()
# use x
requiresInit pragma can also be applied to distinct types.
Given the following distinct type definitions:
type
Foo = object
x: string
DistinctFoo {.requiresInit, borrow: `.`.} = distinct Foo
DistinctString {.requiresInit.} = distinct string
The following code blocks will fail to compile:
var foo: DistinctFoo
foo.x = "test"
doAssert foo.x == "test"
var s: DistinctString
s = "test"
doAssert string(s) == "test"
But these will compile successfully:
let foo = DistinctFoo(Foo(x: "test"))
doAssert foo.x == "test"
let s = DistinctString("test")
doAssert string(s) == "test"