Ok, it's only been a few days of me learning nim, so this may as well be one of the basic things but, Idk. So my problem is that when I make a sequence and pass it's shallow copy to a data type and add to it, only the sequence inside the data type gets added to. To better illustrate this, here's a piece of code
type
lis = ref object of RootObj
v : seq[int]
let s = @[1, 2, 3, 4, 5]
let list = lis()
shallowCopy(list.v, s)
list.v.add(6)
echo list.v
echo s
and it outputs
@[1, 2, 3, 4, 5, 6]
@[1, 2, 3, 4, 5]
but I expected it to output this
@[1, 2, 3, 4, 5, 6]
@[1, 2, 3, 4, 5, 6]
Now, if this can't be done with sequences, can you please point me to a data structure that allows push, pop, and insertion where this can be done. Thanks in advance.I have no idea what shallowCopy(list.v, s) should do in this case.
Your v : seq[int] and your let s = @[1, 2, 3, 4, 5] both defines value types. Well v is a field of a reference to an object, but v is still seq, and seq are value types in Nim, when v get filled with data v allocates its own data buffer and stores its values there. I would guess what you want is v : ref seq[int]. Maybe with
#let s = @[1, 2, 3, 4, 5]
var s = ref seq[int]
s[].add(1) # or s[] = @[1, 2, 3, 4, 5]
list.v = s
@Stefan_Salewski I don't know if I understood your intent properly but I tried doing this,
type
lis = ref object of RootObj
v : ref seq[int]
var s : ref seq[int]
s[] = @[1, 2, 3, 4, 5]
let list = lis()
list.v = s
the runtime threw an illegal storage access error at line 7 where I said s[] = @[1, 2, 3, 4, 5]
, like this
Traceback (most recent call last)
/usercode/in.nim(7) in
/playground/nim/lib/system/assign.nim(147) genericSeqAssign
/playground/nim/lib/system/assign.nim(111) genericAssign
/playground/nim/lib/system/assign.nim(67) genericAssignAux
/playground/nim/lib/system/gc.nim(255) unsureAsgnRef
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
var s = new seq[int]
this should workYes, SolitudeSF is right:
type
lis = ref object of RootObj
v : ref seq[int]
var s : ref seq[int] = new seq[int]
s[] = @[1, 2, 3, 4, 5]
let list = lis()
list.v = s
echo list.v[]
s[].add(13)
echo list.v[]
We have to call new explizit in this case. And I was a bit surprised that we need actually the subscript operator in the second last line, as often the dereference operation is not needed in Nim.