I do not understand why this throws an error. What's the difference? What am I not understanding here?
var s = newSeq[seq[int]](3)
for row in s:
row.add(42)
Error: type mismatch
Expression: add(row, 42)
[1] row: seq[int]
[2] 42: int literal(42)
Expected one of (first mismatch at [position]):
[1] proc add(x: var string; y: char)
[1] proc add(x: var string; y: cstring)
[1] proc add(x: var string; y: string)
[1] proc add[T](x: var seq[T]; y: openArray[T])
[1] proc add[T](x: var seq[T]; y: sink T)
The 'row' inside the loop is of type seq[int] and I can echo it out inside the loop, why can't I add a value to it?
It especially confuses me when I can get the same seq ('row') by indexing into 's' and then I can add to it.
for i, row in s:
s[i].add(42)
You get compile error because item iterator doesn't have var return type: https://nim-lang.org/docs/iterators.html#items.i%2Cseq%5BT%5D
When you modify elements of a seq, you need to use mitem iterator: https://nim-lang.org/docs/iterators.html#mitems.i%2Cseq%5BT%5D
var s = newSeq[seq[int]](3)
for row in s.mitems:
row.add(42)
echo s
Ahhhh. Thanks. That's all I needed to know.
I will say, that in this case (as in others I've come across) I think the compiler could give an error like: Trying to modify immutable object (row.add(42))
That would have explained it to me in 1 second.
I think the compiler could give an error like: Trying to modify immutable object (row.add(42))
It used to do that but it's somewhat hard to get this better error message back. :P
That's really sad to hear and I hope a way can be found to improve these compiler errors.
I say this because the 5 people I have turned on to Nim all loved it at first, but all left it because they didn't understand the compiler errors and therefore ended up getting stuck. 1 went to Rust, 1 to Zig, and the rest just stayed with Python.
I believe it is very important today that the compiler can teach you the language. This is without you first having to learn the 'language' of the compiler or you needing years of experience with C/C++ to have enough low-level understanding.
I've been meaning to make a post about this specific topic because I keep hearing it from people trying out Nim and being a beginner I also run into it myself.
Wow, you people move fast.
These small things make an actual difference for newcomers.
Thank you.
This particular error (a signature that completely matches except for the var part) has tripped me way too many times, so this is a great improvement!
It'd be even better if the compiler could somehow also realise that the problem is due to the implicit items being used and gave you the advice to use mitems instead.