homesalad
homesalad

Reputation: 507

How to get modifyable values from nim Tables

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

Answers (1)

lqdev
lqdev

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:

  • the safer option, just modify the value directly. tables.[] returns a var T for all var Tables:
table["a"].add("bar")
  • the unsafe option, take a pointer to that value and modify that
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

Related Questions