capypad
0 day streak
go / expert
Snippet

Zero-Allocation String to Byte Slice Conversion

Standard conversions copy memory. Using the unsafe package allows reinterpreting the underlying memory header to avoid allocations, though it requires careful management of string immutability.

snippet.go
go
1
2
3
4
5
6
7
func StringToBytes(s string) []byte {
return unsafe.Slice(unsafe.StringData(s), len(s))
}
 
func BytesToString(b []byte) string {
return unsafe.String(unsafe.SliceData(b), len(b))
}
Breakdown
1
unsafe.StringData(s)
Retrieves the pointer to the underlying data of the string without copying.
2
unsafe.Slice(...)
Constructs a new slice header pointing to the existing memory.