Convert between byte slice and string


If you need to manipulate the Unicode characters (as opposed to the individual bytes) of a string, you may want to convert the string to a rune slice.

String to byte slice

When you convert a string to a byte slice, you get a brand new slice that contains the same bytes as the string.

fmt.Println([]byte("abc日")) // [97 98 99 230 151 165]

Byte slice to string

When you convert a slice of bytes to a string, you get a new string that contains the same bytes as the slice.

b := []byte{'a', 'b', 'c', '\xe6', '\x97', '\xa5'}
fmt.Println(string(b)) // abc日


These conversions create a new slice or string, and therefore have time complexity proportional to the number of bytes that are copied.

A string builder can be used to efficiently concatenate strings without redundant copying. See How to best use a string builder.

Further reading

String functions cheat sheet

Share this page: