newbie: string to byte array

77,899 views
Skip to first unread message

Thomas Kaufmann

unread,
Dec 9, 2010, 7:57:45 AM12/9/10
to golang-nuts
Hi,

how can I convert a string in a byte array?

o-o

Thomas

Rob 'Commander' Pike

unread,
Dec 9, 2010, 7:59:16 AM12/9/10
to Thomas Kaufmann, golang-nuts
On Thu, Dec 9, 2010 at 7:57 AM, Thomas Kaufmann <tok...@googlemail.com> wrote:
> Hi,
>
> how can I convert a string in a byte array?

By converting a string [to] a byte array:

[]byte("string")

-rob

Andrew Gerrand

unread,
Dec 9, 2010, 4:57:28 PM12/9/10
to Rob 'Commander' Pike, Thomas Kaufmann, golang-nuts
To expand a little: this is how type conversions work more generally in Go.

To convert variable v to type T, you would do:
T(v)

So, to do the reverse of Rob's example, you can convert the []byte b
to a string like so:
string(b)

Andrew

jimt

unread,
Dec 9, 2010, 6:20:46 PM12/9/10
to golang-nuts
Incidentally, this also works for fetching unicode runes from a string
and in reverse:

runes := []int("foo")
str := string(runes)

fixe...@gmail.com

unread,
Jun 7, 2015, 12:30:52 PM6/7/15
to golan...@googlegroups.com, tok...@googlemail.com
Quick point of clarificaton (for my own understanding): This converts the string to a byte slice, right? Converting to a byte array would imply that the length of the array were statically fixed at compile time, and there's no way to statically guarantee the string has a particular length.

(This is still almost certainly the right thing to do; I just want to confirm I'm not misunderstanding the typing rules in this context).

91ash...@gmail.com

unread,
Jan 19, 2016, 8:34:26 AM1/19/16
to golang-nuts
Thanks 

Roberto Zanotto

unread,
Jan 19, 2016, 10:47:43 AM1/19/16
to golang-nuts, tok...@googlemail.com, fixe...@gmail.com
Yes, this converts the string to a byte slice. If you need a byte array and you know the length of the string at compile time (or an upper bound), you can use copy:
https://play.golang.org/p/yuSjpVu4tl
Reply all
Reply to author
Forward
0 new messages