The thing to realize is that sequences and strings are mutable, and resize via reallocation. This makes things tricky when mutating a shallow string or sequence.
var a = "Hello "
shallow(a)
var b = a # b and a are the same
b.add("world") # The sequence which b points to may or may not need to be reallocated.
In a perfect world, the Nim compiler would be able to optimize away redundant string copy operations. Excepting corner cases, a string doesn't need to be copied to a new variable if it's known that no procedures are called which modify the data the new variable points to.
@Varriount
I fail to understand what shallow() and shallowCopy() does :(
var a = "Hello "
shallow(a)
var b = a # b and a are the same
var c: string
shallowCopy(c,b)
echo addr(a[0]).repr, addr(b[0]).repr, addr(c[0]).repr
Above code shows different addresses for the strings data. Shouldn't this be not the case?
What do you mean with b and a are the same?
UPDATE: Well I actually found what made that confusing to me.
block:
var a = "Hello "
shallow(a)
var b = a # b and a are the same
echo addr(a).repr
echo addr(b).repr
b.add("world") # The sequence which b points to may or may not need to be reallocated.
echo addr(a).repr # defective now
echo addr(b).repr
Output:
ref 0x7fff53758590 --> 0x10c517050"Hello "
ref 0x7fff53758588 --> 0x10c517050"Hello "
ref 0x7fff53758590 --> 0x10c517050""
ref 0x7fff53758588 --> 0x10c51b290"Hello world"
This is more what I expected. The "block:" is the changing factor. So shallow()/shallowCopy() does not do anything for the globals (including not telling that it does nothing).