On Monday, 12 April 2021 at 17:01:38 UTC+1 theluk...@gmail.com wrote: > I've heard several times from members of the community (on Matrix and > possibly on answers) that a simple iteration like > > const mixed = "\b5Ὂg̀9! ℃ᾭG" > for _, c := range mixed { > ... do something with c (but not write to it) > > will actually silently allocate a slice of runes and decode the string > into it, before iteration. I've heard it is done to prevent problems that > occur when a programmer might overwrite data being iterated, which should > be a no-brainer for programmers in general, but sure, whatever. So is it > true in the case for constants? Is it true always, or only when writes > occur to the source string or `c` in that case? >
Writing to c won't make any difference (because it's a completely separate variable, an int32 which doesn't share any memory with the original string); and writing to the source string is impossible (because strings are immutable in go). Could it be possible that you're thinking of the opposite case? Given an input slice b []byte, if you choose to iterate over it as a series of UTF-8 codepoints using for _, c := range string(b) { ... } then I would expect the string(b) conversion to make a byte-for-byte copy of b, because a string is immutable but b isn't. https://play.golang.org/p/3TN2TwdEhk7 This isn't the same as exploding the string into a slice of int32 runes up-front, but it might explain where the rumour came from. -- 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. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c9e5ca88-29c7-4b6e-973f-295d8cfeb3cen%40googlegroups.com.