Issue
Let’s convert string
to []byte
:
func toBytes(s string) []byte {
return []byte(s) // What happens here?
}
How expensive is this cast operation? Is copying performed? As far as I see in Go specification: Strings behave like slices of bytes but are immutable, this should involve at least copying to be sure subsequent slice operations will not modify our string s
. What happens with reverse conversation? Does []byte <-> string
conversation involve encoding/decoding, like utf8 <-> runes?
Solution
The []byte(s)
is not a cast but a conversion. Some conversions are the same as a cast, like uint(myIntvar)
, which just reinterprets the bits in place. Unfortunately that’s not the case of string to byte slice conversion. Byte slices are mutable, strings (string values to be precise) are not. The outcome is a necessary copy (mem alloc + content transfer) of the string being made. So yes, it can be costly in some scenarios.
EDIT: No encoding transformation is performed. The string (source) bytes are copied to the slice (destination) bytes as they are.
Answered By – zzzz
Answer Checked By – Katrina (BugsFixing Volunteer)