create a reference to an array in Nim
Asked Answered
D

2

8
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.

Dost answered 1/6, 2015 at 22:8 Comment(0)
I
12

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.

Isomer answered 1/6, 2015 at 23:9 Comment(0)
A
1
var x: array[5, int]
type ArrRef = ref array[5, int]
var y, z : ArrRef
x = [1, 2, 3, 4, 5]
y = cast[ArrRef](x.addr)
  # addr provides a ptr type
  # cast to convert ptr to ref

z = y
echo "x ", x, " is ", x.addr.repr
  # repr is a lower-level version of the $ to-string operator
echo "y ", y[], " is ", y.addr.repr  
  # [] is dereference, so c[] --> b
echo "z ", z[], " is ", z.addr.repr
  # all [1, 2, 3, 4, 5]


z[4] = 10
echo ""
echo "x ", x, " is ", x.addr.repr
echo "y ", y[], " is ", y.addr.repr 
echo "z ", z[], " is ", z.addr.repr
  # all [1, 2, 3, 4, 10]

new(z)
  # use new() to allocate space for the value to be referenced
z[] = x
z[4] = 20
echo ""
echo "x ", x, " is ", x.addr.repr
echo "y ", y[], " is ", y.addr.repr 
echo "z ", z[], " is ", z.addr.repr
  # only z is [1, 2, 3, 4, 20]
Affidavit answered 26/7, 2023 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.