What are strings in Nimes?

From what I understand, strings in Nim are basically a mutable sequence of bytes and that they are copied when assigned.

Given this, I assumed that sizeof will tell me (e.g. len ) the number of bytes, but instead it always gives 8 on my 64-bit machine, so it seems to hold the pointer.

Given that I have the following questions ...

  • What was the motivation for copying on assignment? Is it because they are mutable?

  • Is there a time when it is not copied at the appointment? (I assume that the function parameters are not var not copied. Anything else?)

  • Are they optimized so that they are only copied if / when they are mutated?

  • Is there a significant difference between a string and a sequence, or are the answers to the above questions equally applicable to all sequences?

  • Anything else overall worth noting?

Thanks!

+8
string nim
source share
1 answer

The string definition is actually located in system.nim , just under a different name:

 type TGenericSeq {.compilerproc, pure, inheritable.} = object len, reserved: int PGenericSeq {.exportc.} = ptr TGenericSeq UncheckedCharArray {.unchecked.} = array[0..ArrayDummySize, char] # len and space without counting the terminating zero: NimStringDesc {.compilerproc, final.} = object of TGenericSeq data: UncheckedCharArray NimString = ptr NimStringDesc 

Thus, the string is a raw pointer to an object with the fields len , reserved and data . Processes for strings are defined in sysstr.nim .

The semantics of the string assignments were chosen the same way as for all value types (not ref or ptr) in Nim by default, so you can assume that the assignments create a copy. When a copy is not needed, the compiler can leave it, but I'm not sure how much this happens. Passing strings to proc does not copy them. There is no optimization that prevents lines from being copied until they are mutated. Sequences behave identically.

You can change the default behavior for the default rows and sections by marking them as shallow, then copying is not performed on assignment:

 var s = "foo" shallow s 
+10
source share

All Articles