How to initialize objects and arrays and not have the Warning: Cannot prove
that 'result' is initialized. This will become a compile time error in the
future. [ProveInit] message? My goal is not to disable that compiler warning
with compiler flags or pragma, but to write the correct code for the nim
compiler.
When the default value of a type is not compatible with the default value of a
composed type (i.e. object), the compiler complains when you start using that
object if it is not correctly initialized. For an object, the way to avoid the
[ProveInit] warning is to use the default type converter, like:
type
Val = range[10 .. 100]
Mu = object
i: int
j: Val
proc initMu(i: int, j: Val): Mu =
result = Mu(i: i, j: j)
proc initMumu(i: int, j: int): Mu =
result = Mu(i: i, j: j)
var
m: Mu
m = initMu(1, 20)
echo m
m = initMumu(1, 20)
echo m
Run
But when initializing arrays, the compiler is more strict and I haven't found
the way to initialize them without warnings.
type
Val = range[10 .. 100]
Ga = array[3, Val]
Gaga = array[2, array[2, Val]]
proc initGa(a: openArray[int]): Ga =
# Ga() converter not compatible with openArray
#result = Ga(a)
# Initializing item by item gives warnings
for i in low(a) .. high(a):
result[i] = Val(a[i])
proc initGaga(a: array[2, array[2, Val]]): Gaga =
result = Gaga(a)
var
n: Ga
r: Gaga
n = initGa([20, 25, 30])
echo n
# Will not compile
#r = initGaga([[10, 20], [30, 40]])
r = initGaga([[Val(10), 20], [Val(30), 40]])
echo r
Run
There are some parts of my code where I can prove that an array is correctly
initialized, so I could disable the compiler warning locally. But there are
other parts where I can't prove it easily and if it's not the case, there's a
bug in my algorithm and I want the assistance of the compiler to warn me of
such cases.
How can it be done?