nim-lang

Field identifiers inside a nim tuple


according to the manual which mentions @ Tuple or object scope ... To the end of the tuple/object definition, I though it's possible to access field elements of an array or tuple inside the corresponding data type like in C where int a[]={10, a[0] + 10} is possible?

How can I create an array or tuple like var a = (x: 10, y: x + 10), because actually the parser quits with undeclared identifier x?

Do I need RTII for this kind of access?

Thanks in advance, Marcello


Solution

  • Don't think that's possible in nim, but you could use a template to get around:

    template makeTuple(input: untyped): untyped =
      (x: input, y: input + 10)
    
    template plus10(input: untyped): untyped =
      (x: input, y: input + 10)
    
    var a = makeTuple(2)
    echo a
    var b = 3.5.plus10
    echo b
    

    This will output:

    (x: 2, y: 12)
    (x: 3.5, y: 13.5)