Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a reference to an array in Nim

var b: array[5, int]

type
    ArrRef = ref array[5, int]

var c : ArrRef
echo repr(c) # nil
c = addr b # doesn't compile, says type is Array constructor, expected reference

In Nim, how can I pass references to arrays instead of passing by value? See the above code for what I have so far.

like image 917
talloaktrees Avatar asked Jun 01 '15 22:06

talloaktrees


People also ask

Can we create array of reference?

An array of references is illegal because a reference is not an object. According to the C++ standard, an object is a region of storage, and it is not specified if a reference needs storage (Standard §11.3. 2/4). Thus, sizeof does not return the size of a reference, but the size of the referred object.

How do I run a NIM program?

After a successful compilation, we can run our program. On Linux we can run our program by typing ./helloworld in the terminal, and on Windows we do it by typing helloworld.exe . c is telling Nim to compile the file, and -r is telling it to run it immediately.


1 Answers

In Nim refs are on the heap and have to be allocated with new. You can't just use a stack array as a ref because that would be unsafe: When the array disappears from the stack, the ref points to some wrong memory. Instead you have two choices: You can use unsafe ptrs instead. Other than refs, they are not garbage collected and can be used for unsafe stuff. Alternatively you can make b a ref array directly.

like image 160
def- Avatar answered Oct 24 '22 22:10

def-