does Go make a copy for []byte("hello") conversion?

1,509 views
Skip to first unread message

Riwen Huang

unread,
Jun 4, 2011, 11:09:48 AM6/4/11
to golang-nuts
HI, 

for source:

  a := []byte("hello")
  a[0] = 10

  the "hello" is a constant string, the a[0] assignment works because the Go do something like

a := make ([]byte, len("string"))
copy(a, "hello")

the variable 'a'  point to the new allocated array, not the string "hello", right? Or  the variable 'a' just point the the underly string "hello" only, and no new array allocated? 

thanks, 

Rwen
  

John Asmuth

unread,
Jun 4, 2011, 11:20:02 AM6/4/11
to golan...@googlegroups.com
Without using the unsafe package, you cannot have a []byte that points to the same data as a string. []byte(astring) makes a copy.

Otherwise strings wouldn't be immutable.

Steven

unread,
Jun 4, 2011, 1:52:12 PM6/4/11
to golan...@googlegroups.com
On Saturday, June 4, 2011, John Asmuth <jas...@gmail.com> wrote:
> Without using the unsafe package, you cannot have a []byte that points to the same data as a string. []byte(astring) makes a copy.
> Otherwise strings wouldn't be immutable.

I think the question is, does this conversion expression allocate a
byte array each for the string and the []byte, initialize the string,
then copy its contents to the []byte, or does it just allocate one
byte array, initialize it, then return a []byte referring to that
memory?

Andrew Gerrand

unread,
Jun 5, 2011, 8:02:28 PM6/5/11
to Riwen Huang, golang-nuts

Only the []byte is allocated at runtime. The const string is part of
the program's data segment. (I think.)

Andrew

Rob 'Commander' Pike

unread,
Jun 5, 2011, 8:47:51 PM6/5/11
to Andrew Gerrand, Riwen Huang, golang-nuts

The []byte will just be a slot on the stack and the underlying data for the slice will be allocated on the heap, essentially as outlined here (except it should read len("hello")).

-rob


Reply all
Reply to author
Forward
0 new messages