Package unsafe
…
The function
String
returns a string value whose underlying bytes start atptr
and whose length islen
. The same requirements apply to theptr
andlen
argument as in the functionSlice
. Iflen
iszero
, 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
StringData
returns a pointer to the underlying bytes of thestr
argument. 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
[]byte
instead (and thebytes
package, instead of thestrings
package for common maninpulations) - Ues a
strings.Builder
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)