Appending a string to a byte slice

1,061 views
Skip to first unread message

Jeffrey

unread,
Jun 22, 2011, 9:43:27 PM6/22/11
to golang-nuts
The copy function handles as a special case copying a string directly
to a byte slice. Why doesn't the built-in append function behave
similarly?

It would be nice to say
s := make([]byte, 32)
copy(s, "hello, ")
append(s, "world!")
but instead the last line needs to be:
s = append(s, []byte("world!")...)

Jeffrey

unread,
Jun 22, 2011, 9:44:58 PM6/22/11
to golang-nuts
Correction: I meant to say
s = append(s, "world!")

Ostsol

unread,
Jun 22, 2011, 10:22:14 PM6/22/11
to golang-nuts
I'm guessing the reason is that 'copy' takes two slices as parameters,
while append takes a slice plus a variable number of additional
parameters, each of which is of the same type as the first parameter's
elements. A string is not a byte, and you are not unpacking the
string into its component bytes. Asking the language to implicitly
unpack the string strays from the built-in's definition. Perhaps
explicit unpacking with implicit conversion should be allowed,
though. For example:

s = append(s, "world!"...)

-Daniel
Reply all
Reply to author
Forward
0 new messages