I've just been writing some code involving sequences and I wanted to add a sequence to an existing sequence. A simple example like this works...
var s1 = @["abc", "def"]
var s2 = @["ghi", "hjk", "lmn"]
s1.add(s2)
echo s1
# @[abc, def, ghi, hjk, lmn]
...so I know it's possible.
There's something different about the following (extracted) example, which doesn't work:
type
Packet = object
code: int
data: seq[string]
proc processData(data: seq[string], packet: var Packet): bool =
var storedPackets {.global.}: seq[Packet] = newSeq[Packet](0)
packet.data = data[4..^1]
for storeIndex, storedPacket in storedPackets:
if packet.code == storedPacket.code:
storedPacket.data.add(packet.data) # ERROR
test.nim(11, 30) Error: type mismatch: got (seq[string], seq[string])
but expected one of:
proc add(x: var string; y: string)
proc add[T](x: var seq[T]; y: T)
proc add(x: var string; y: char)
proc add[T](x: var seq[T]; y: openArray[T]) ### I think this should match!
proc add(x: var string; y: cstring)
As I understand it, an openArray accepts either an array or a seq, so if it expects (seq[T], openArray[T]) and got (seq[string], seq[string]) it should be happy, but I'm obviously missing something...
I've tried calling it as add(x=storedPacket.data, y=packet.data), but the only thing that changes is that it adds the x and y into the braces after "got" on the first line. The error message really isn't helping me figure out what to change...
Please can someone tell me what I'm doing wrong here?
Try this line for mutability of the elements:
for storedPacket in storedPackets.mitems:
It did - sort of - by mentioning that it expected a var argument, but I agree, it could be clearer. BTW, there is also an mpairs iterator, if you need to use the index as well (but only the element is mutable, not the index):
for storeIndex, storedPacket in storedPackets.mpairs: