问题
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.
回答1:
In Nim ref
s 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 ptr
s instead. Other than ref
s, they are not garbage collected and can be used for unsafe stuff. Alternatively you can make b
a ref array
directly.
来源:https://stackoverflow.com/questions/30584140/create-a-reference-to-an-array-in-nim