Reputation: 507
I'm totally new to Nim, and am trying to modify values in a table. Specifically, I'd like to append items to a sequence stored as a value in a table. My current code looks like:
import tables
var table = initTable[string, seq[string]]()
table["a"] = @["foo"]
var x = table["a"]
x.add("bar")
echo $table
The table entry "a" just contains ["foo"] and not ["foo", "bar"], which I'm guessing is because accessing table["a"] is returning a copy of the sequence that was originally inserted. How do I access (a reference to) the original seq, and not a copy? Thank you!
Upvotes: 2
Views: 736
Reputation: 403
Your problem is on the line:
var x = table["a"]
This actually makes a copy of what's stored in table["a"]
. Because seqs are pass-by-copy, this copies all the data stored in the seq into a new seq stored in x
. If you want a reference to the seq stored in the table, you have two options:
tables.[]
returns a var T
for all var Table
s:table["a"].add("bar")
var x = addr table["a"]
x[].add("bar")
However I would advise against using pointers unless you're absolutely sure you know what you're doing. There's also an experimental feature: view types. However, it's not yet stable and even this simple example fails with a SIGSEGV (as of 1.4.2):
var x: var seq[string] = table["a"]
x.add("bar")
Upvotes: 4