Yes… I’ve started coding in Go recently. It lacks many things but the one feature relevant to this post is const keyword. Arrays and slices in particular are always mutable and so equivalent of C’s const char * does not exist.
On the other hand, strings are immutable which means that conversion between a string and []byte requires memory allocation and copying of the data1. Often this might be acceptable but to squeeze every last cycle the following two functions might help achieve zero-copy implementation:
func String(bytes []byte) string {
hdr := *(*reflect.SliceHeader)(unsafe.Pointer(&bytes))
return *(*string)(unsafe.Pointer(&reflect.StringHeader{
Data: hdr.Data,
Len: hdr.Len,
}))
}
func Bytes(str string) []byte {
hdr := *(*reflect.StringHeader)(unsafe.Pointer(&str))
return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: hdr.Data,
Len: hdr.Len,
Cap: hdr.Len,
}))
}Depending on the length of the strings, the difference in performance might be noticeable: