How can I get the following code run?
type: Object = object
size: int
list0 : array[size, int]
list1 : array[size, string]
list2 : array[size, float]
As shown above, I would like to use the field size to determine the size of the array list s.
I found the (assumingly) correct way.
type
Object[size: static[int]] = object
list : array[size, int]
size : static[int]
#[
size = size
# won't work for now but in the future...
# https://github.com/nim-lang/Nim/issues/3250
]#
as for now, I believe I need to use a constructer
My problem here is
Your problem is, that you do not understand that an array in Nim has fixed size specified at compile time. So your code as shown in your first message here makes no sense. As Mr LemonBoy told you, you may try to make desired size a compile time parameter of your object data type, or you may use seq data type instead of array, as seq size is dynamic.
Yes, with term "compile time parameter" I indicated that in
var o: Object[2]
literal 2 is a value known at compile time. Instead of a literal it can be a const defined earlier, but not a value defined with let or var keyword. If you later need that value, you have it available from list0.len.
For future readers... The constructor I mentioned above.
proc initObject[size]() : Object[size] =
result = Object[size](size: size)
You don't need that size field, if that is to always equal the initial size parameter - it has to keep the same value in all instances and yet occupy memory (4-8 bytes) in each of them. Compiler remembers the generic parameter and can return it to you:
type
Object[size: static[int]] = object
list0 : array[size, int]
list1 : array[size, string]
list2 : array[size, float]
var o: Object[2]
echo o.size # Not a field, but rather a per-type constant
Aside from not occuping memory at run-time, this way it cannot be changed and so always keeps the correct value (o.size = 3 won't compile).
# the wrong way
type
Object[size: static[int]] = object
size: int
list0 : array[size, int]
list1 : array[size, string]
list2 : array[size, float]
var o: Object[2]
o.size = 3
echo o.size # => 3; an irrelevant value
Thank you for your advice! Just that ,totally embarrassingly, I don't know how to run the proc...
Would you provide me an example?
It's called the same way, N is taken from the object itself.
type
Object[size: static[int]] = object
list0 : array[size, int]
list1 : array[size, string]
list2 : array[size, float]
var o: Object[2]
echo o.size
proc size1[N](x: Object[N]): int = N
echo o.size1
template size2[N](x: Object[N]): int = N
echo o.size2
Ah, I see!
Thanks a lot.