Lets ignore the fact that this is Go for a second. The first thing you need is a serialization format to marshal the []string into.

There are many option here. You could build your own or use a library. I am going to assume you don't want to build your own and jump to serialization formats go supports.

In all examples, data is the []string and fp is the file you are reading/writing to. Errors are being ignored, check the returns of functions to handle errors.

Gob

Gob is a go only binary format. It should be relatively space efficient as the number of strings increases.

enc := gob.NewEncoder(fp)
enc.Encode(data)

Reading is also simple

var data []string
dec := gob.NewDecoder(fp)
dec.Decode(&data)

Gob is simple and to the point. However, the format is only readable with other Go code.

Json

Next is json. Json is a format used just about everywhere. This format is just as easy to use.

enc := json.NewEncoder(fp)
enc.Encode(data)

And for reading:

var data []string
dec := json.NewDecoder(fp)
dec.Decode(&data)

XML

XML is another common format. However, it has pretty high overhead and not as easy to use. While you could just do the same you did for gob and json, proper xml requires a root tag. In this case, we are using the root tag "Strings" and each string is wrapped in an "S" tag.

type Strings struct {
    S []string
}

enc := xml.NewEncoder(fp)
enc.Encode(Strings{data})

var x Strings
dec := xml.NewDecoder(fp)
dec.Decode(&x)
data := x.S

CSV

CSV is different from the others. You have two options, use one record with n rows or n records with 1 row. The following example uses n records. It would be boring if I used one record. It would look too much like the others. CSV can ONLY hold strings.

enc := csv.NewWriter(fp)
for _, v := range data {
    enc.Write([]string{v})
}
enc.Flush()

To read:

var err error
var data string
dec := csv.NewReader(fp)
for err == nil {        // reading ends when an error is reached (perhaps io.EOF)
    var s []string

    s, err = dec.Read()
    if len(s) > 0 {
        data = append(data, s[0])
    }
}

Which format you use is a matter of preference. There are many other possible encodings that I have not mentioned. For example, there is an external library called bencode. I don't personally like bencode, but it works. It is the same encoding used by bittorrent metadata files.

If you want to make your own encoding, encoding/binary is a good place to start. That would allow you to make the most compact file possible, but I hardly thing it is worth the effort.

Answer from Stephen Weinberg on Stack Overflow
Top answer
1 of 8
31

Lets ignore the fact that this is Go for a second. The first thing you need is a serialization format to marshal the []string into.

There are many option here. You could build your own or use a library. I am going to assume you don't want to build your own and jump to serialization formats go supports.

In all examples, data is the []string and fp is the file you are reading/writing to. Errors are being ignored, check the returns of functions to handle errors.

Gob

Gob is a go only binary format. It should be relatively space efficient as the number of strings increases.

enc := gob.NewEncoder(fp)
enc.Encode(data)

Reading is also simple

var data []string
dec := gob.NewDecoder(fp)
dec.Decode(&data)

Gob is simple and to the point. However, the format is only readable with other Go code.

Json

Next is json. Json is a format used just about everywhere. This format is just as easy to use.

enc := json.NewEncoder(fp)
enc.Encode(data)

And for reading:

var data []string
dec := json.NewDecoder(fp)
dec.Decode(&data)

XML

XML is another common format. However, it has pretty high overhead and not as easy to use. While you could just do the same you did for gob and json, proper xml requires a root tag. In this case, we are using the root tag "Strings" and each string is wrapped in an "S" tag.

type Strings struct {
    S []string
}

enc := xml.NewEncoder(fp)
enc.Encode(Strings{data})

var x Strings
dec := xml.NewDecoder(fp)
dec.Decode(&x)
data := x.S

CSV

CSV is different from the others. You have two options, use one record with n rows or n records with 1 row. The following example uses n records. It would be boring if I used one record. It would look too much like the others. CSV can ONLY hold strings.

enc := csv.NewWriter(fp)
for _, v := range data {
    enc.Write([]string{v})
}
enc.Flush()

To read:

var err error
var data string
dec := csv.NewReader(fp)
for err == nil {        // reading ends when an error is reached (perhaps io.EOF)
    var s []string

    s, err = dec.Read()
    if len(s) > 0 {
        data = append(data, s[0])
    }
}

Which format you use is a matter of preference. There are many other possible encodings that I have not mentioned. For example, there is an external library called bencode. I don't personally like bencode, but it works. It is the same encoding used by bittorrent metadata files.

If you want to make your own encoding, encoding/binary is a good place to start. That would allow you to make the most compact file possible, but I hardly thing it is worth the effort.

2 of 8
12

The gob package will do this for you http://godoc.org/encoding/gob

Example to play with http://play.golang.org/p/e0FEZm-qiS

same source code is below.

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
)

func main() {
    // store to byte array
    strs := []string{"foo", "bar"}
    buf := &bytes.Buffer{}
    gob.NewEncoder(buf).Encode(strs)
    bs := buf.Bytes()
    fmt.Printf("%q", bs)

    // Decode it back
    strs2 := []string{}
    gob.NewDecoder(buf).Decode(&strs2)
    fmt.Printf("%v", strs2)
}
🌐
Reddit
reddit.com › r/golang › converting string ⇔ []byte
r/golang on Reddit: Converting string ⇔ []byte
July 12, 2023 -

Most programs should probably just cast between the two types:

s1 := "this is a string"
b := ([]byte)(s1)
s2 := (string)(b)

However, note that casting involves copying the data. This is because Go strings are immutable, so copying is necessary to ensure correctness. (BTW, Rust does this differently because it ensures immutability via ownership.)

That said, in some specific cases programmers might prefer to avoid copying data in order to save memory and improve performance for large amounts of data.

I think this is the best way to achieve it in Go 1.20+:

// This conversion *does not* copy data. Note that casting via "(string)([]byte)" *does* copy data.
// Also note that you *should not* change the byte slice after conversion, because Go strings
// are treated as immutable. This would cause a segmentation violation panic.
func BytesToString(bytes []byte) string {
	return unsafe.String(unsafe.SliceData(bytes), len(bytes))
}

// This conversion *does not* copy data. Note that casting via "([]byte)(string)" *does* copy data.
// Also note that you *should not* change the byte slice after conversion, because Go strings
// are treated as immutable. This would cause a segmentation violation panic.
func StringToBytes(string_ string) (bytes []byte) {
	return unsafe.Slice(unsafe.StringData(string_), len(string_))
}

This is indeed the approach you see in the strings.Builder source code.

Note the very important warning that you should never change the byte arrays after using these functions. It would result in a SIGSEGV panic.

For the first function, I've used this in the past:

func BytesToString(bytes []byte) string {
	return *(*string)(unsafe.Pointer(&bytes))
}

This works, but I wonder what the trade-offs are versus the approach above. Length does not have to be extracted here, but are there edge cases that would cause problems? Or are the two approaches entirely equivalent?

For the second function, I've used this in the past, however it should not be used anymore because StringHeader and SliceHeader are to be deprecated in Go 1.21. Including it here for reference:

func StringToBytes(string_ string) (bytes []byte) {
	stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&string_))
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))
	sliceHeader.Data = stringHeader.Data
	sliceHeader.Cap = stringHeader.Len
	sliceHeader.Len = stringHeader.Len
	return
}

Other relevant reference material:

  • https://github.com/golang/go/issues/25484

  • https://github.com/golang/go/issues/19367

  • https://github.com/golang/go/issues/53003#issuecomment-1140276077

Discussions

Convert string array to byte array in go - Stack Overflow
Given an string array which only contains single characters such as: ex := [...]string{"a","o",".",".","2",".",".","9"... More on stackoverflow.com
🌐 stackoverflow.com
go - How to assign string to bytes array - Stack Overflow
Best coding practices in Go is ... a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread 2016-02-14T00:44:04.653Z+00:00 ... The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array. 2016-02-14T05:17:24.167Z+00:00 ... For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/s... More on stackoverflow.com
🌐 stackoverflow.com
types - How to convert byte array to string in Go - Stack Overflow
The easiest method I use to convert byte to string is: ... Why the :? What's the difference between this answer and myString := string(myBytes)? 2021-12-14T09:19:41.64Z+00:00 ... The : is needed because byte arrays cannot be directly turned to a string while slices can. More on stackoverflow.com
🌐 stackoverflow.com
proposal: Go 2: permit converting a string constant to a byte array type
There was an error while loading. Please reload this page · byte slices and strings are convertable to each other: More on github.com
🌐 github.com
52
January 30, 2020
🌐
YourBasic
yourbasic.org › golang › convert-string-to-byte-slice
Convert between byte array/slice and string · YourBasic Go
See Convert between rune array/slice and string. When you convert a string to a byte slice, you get a new slice that contains the same bytes as the string.
🌐
Go language Tutorial
golangtutorial.dev › home › tips › convert a string to byte array or slice in go
Convert a String To Byte Array or Slice in Go - Go language Tutorial
December 13, 2020 - I wrote a go program (‘convert-string-to-byte-array.go’) which convert a string to byte slice and prints it in the command prompt.
🌐
Bacancy Technology
bacancytechnology.com › qanda › golang › assign-string-to-bytes-array
Mastering Go: How to Assign String to Bytes Array
December 13, 2023 - Each character in the string corresponds to a byte in the resulting array. Another approach to convert a string to a byte array involves directly assigning the string to a byte array variable using type casting.
🌐
Delft Stack
delftstack.com › home › howto › go › golang string to byte array
How to Convert String to Byte Array in Golang | Delft Stack
February 12, 2024 - The copy() function in Golang converts a string to a byte array that involves copying the characters of the string into a pre-allocated byte array.
Find elsewhere
🌐
gosamples
gosamples.dev › tutorials › convert string to []byte or []byte to string in go
🖨️ Convert string to []byte or []byte to string in Go
October 13, 2021 - To convert a string to a byte slice in Go, use the standard []byte conversion expression []byte(string).
🌐
Tutorial Gateway
tutorialgateway.org › golang-string-to-byte-array
Golang String to Byte Array
January 30, 2025 - In this example, []byte(strToConvert) will convert the string to a byte array.
🌐
TutorialsPoint
tutorialspoint.com › article › golang-program-to-convert-string-value-to-byte-value
Golang Program to Convert String Value to Byte Value
October 7, 2023 - In the first example, we have used the []byte(string) function to convert the string value to byte values. In the second example we have used two built-in functions of golang, make () function and copy () function to convert the string values ...
🌐
GitHub
github.com › arungudelli › go › blob › main › content › en › tips › string-to-byte-array-go.md
go/content/en/tips/string-to-byte-array-go.md at main · arungudelli/go
We can use byte array to store a collection of binary data, for example, the contents of a file. The above code to convert string to byte slice is very useful while using ioutil.WriteFile function, which accepts a bytes as its parameter:
Author: arungudelli
🌐
DEV Community
dev.to › jones_charles_ad50858dbc0 › optimize-your-go-code-mastering-string-and-byte-conversions-3k5
Optimize Your Go Code: Mastering `string` and `[]byte` Conversions - DEV Community
September 3, 2025 - A string in Go is a read-only sequence of bytes—think of it as text carved in stone. You can’t modify it without creating a new copy. Internally, it’s just two fields: Data: A pointer to a byte array.
🌐
Leapcell
leapcell.io › blog › how-to-convert-a-string-to-bytes-in-golang
How to Convert a String to Bytes in Golang | Leapcell
July 25, 2025 - Converting a string to bytes in Golang is simple and efficient using []byte(str).
🌐
GitHub
github.com › golang › go › issues › 36890
proposal: Go 2: permit converting a string constant to a byte array type · Issue #36890 · golang/go
January 30, 2020 - byte slices and strings are convertable to each other: var bs = []byte("şevkı") fmt.Println(len(bs), string(bs)) I propose to extend this by allowing to convert: string constants to byte arrays: var ba = [...]byte("şevkı") byte arrays to...
Author: golang
🌐
Golang 101
golang101.com › questions › how-to-convert-string-to-byte-in-golang
How to Convert a String to a Byte in Go - Golang 101
October 13, 2023 - The output is an array of bytes where each byte represents a character in the original string. Another way to convert a string to a byte array is by using the strings.Bytes() function from the standard library.
🌐
Sentry
sentry.io › sentry answers › go › assigning a string to a byte array in go
Go Assign a String to a Byte Array or Byte Slice | Sentry
2 weeks ago - Convert a Go string to a byte slice directly with a type conversion, or use the copy function to fill a fixed-length byte array while handling UTF-8
🌐
Google Groups
groups.google.com › g › golang-nuts › c › GxBB67KaLuc
[]byte and string convert?
January 29, 2021 - Generally yes. As strings are immutable, and []byte is not, if you convert from string -> []byte, you need a new copy which can be written without changing the original string (which may be referred to elsewhere). If you convert from []byte -> string, then you need a new copy so that any later changes to the byte slice won't change the contents of the string.
🌐
Educative
educative.io › answers › how-to-convert-a-golang-string-into-bytes
How to convert a Golang string into bytes
In the code snippet below, we will convert the string abcdef into a slice of bytes: ... In line 5, we import the fmt package, which is useful for printing statements. In line 9, the program execution starts from the main() function in Golang.