How expensive is []byte(string)?

前端 未结 2 1959
深忆病人
深忆病人 2020-12-14 17:10

Let\'s convert string to []byte:

func toBytes(s string) []byte {
  return []byte(s) // What happens here?
}

How e

2条回答
  •  旧巷少年郎
    2020-12-14 17:55

    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.

提交回复
热议问题