Let\'s convert string to []byte:
func toBytes(s string) []byte {
return []byte(s) // What happens here?
}
How e
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.