Package unsafe
…
The function
Stringreturns a string value whose underlying bytes start atptrand whose length islen. The same requirements apply to theptrandlenargument as in the functionSlice. Ifleniszero, the result is the empty string"". Since Go strings are immutable, the bytes passed to String must not be modified afterwards. [Go 1.20]The function
StringDatareturns a pointer to the underlying bytes of thestrargument. For an empty string the return value is unspecified, and may benil. Since Go strings are immutable, the bytes returned by StringData must not be modified [Go 1.20].
As mentioned twice above, and also discussed many times before, strings in Go are immutable. This means that making changes to strings requires making in-memory copies, and this can be inefficient.
This is why these two functions are sometimes used when high performance is essential, and if you’re willing to violate the string immutability rule of Go. This is package unsafe, after all!
It’s not advised to do this, however. And I’m not even going to show you how.
Instead, I’ll suggest, if you’re working on performance critical code, and string modification is your bottleneck, almost always, there are better approaches, such as:
- Use
[]byteinstead (and thebytespackage, instead of thestringspackage for common maninpulations) - Ues a
strings.Builder
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)