On Tue, Aug 28, 2018 at 6:45 PM Jay Sharma <jaysharma...@gmail.com> wrote:
> @Jan, The example you shown it is copying a string to new variable. but my question was related to same variable. > Will it overwrite the same memory or it will create some copy ? The same concept applies as before. String variables are unique, mutable and independent entities, string values are possibly shared, meaning different string variables can point to the same string value. IOW, reasignment of 'x' mutates x but not what 'x' points to. In case of a string literal, like in "foo" or "bar", no memory is ever written or allocated wrt the string value. All literals are fixed at compile time to reside in the text, read only segment of the program. Assigning "foo" to 'x' or "bar" to 'x' just mutates 'x' to point to "foo" or "bar" respectively. The only thing mutated is the variable. The memory occupied by the variable is overwritten, the string value it points to is not. Assignment of a string value/expression does not copy the string value. Instead it copies/writes the pointer to the string value into the string variable. More details can be found for example here: https://research.swtch.com/godata PS: It's like C char* pointers to a certain extent. Except Go strings know their length without need to search for the NULL terminator - so they also can include zero bytes. Moreover, different string variables can point to different characters of the same string value. Thanks to that, if you slice a string, like in `s = s[lo:hi]`, it's again an O(1) operation (as is len(s)). All of that is enabled by the imutability of string values. Compare to slices. After 'a := []int{1, 2, 3}; b := a; b[1] = 42', a[1] == 42 is true. However, one cannot do the same with strings. s[expr] = 'X' is illegal if s is of a string type. -- -j -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.