我可以破坏[] byte和字符串之间的数据转换吗?

In Go, if I convert from a string -> []byte or conversely, from []byte -> string, could the data ever get corrupted. For example, let's say I've defined:

fooBytes := []byte(fooString)
fooConvertedBack := string(fooBytes
fooBytesConvertedBack := []byte(fooConvertedBack)

Then could we get a case where data gets corrupted such that:

fooString != fooConvertedBack
fooBytes != fooBytesConvertedBack

I'm guessing the answer here is no. I'm working with random arrays of bytes and I want to make sure that I won't corrupt data because, say for example, a golang string has a default character set which doesn't allow for completely random bytes.

Is it better to base64 encode the bytes?

As Cerise Limón wrote, it won't be corrupted. Converting between string and []byte does not interpret the bytes, it just copies them as-are.

Do note however that if you would convert between string and []rune, that might change the content becase as written in Spec: Conversions to and from a string type:

Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string.

So this conversion decodes the runes (Unicode codepoints), and if the input string is not a valid UTF-8 encoded text, the Unicode replacement character 0xFFFD will be used in such cases.

For example a string containing a single 0xff byte is not a valid UTF-8 encoded text:

fooString := "\xff"
barString := string([]rune(fooString))
fmt.Println(fooString == barString)
fmt.Printf("%x %x", fooString, barString)

Outputs (try it on the Go Playground):

false
ff efbfbd

(Note: the hex efbfdb is the 3-byte UTF-8 encoded value of the Unicode replacement character 0xFFFD.)

You can convert a string to []byte or vice versa, SAFELY.

From the golang spec:

A string value is a (possibly empty) sequence of bytes.

Also from the official blog:

In Go, a string is in effect a read-only slice of bytes.

No, the data will not be corrupted. The conversions copy the bytes with no interpretation of what those bytes are. Here are the relevant sentences from the specification:

Converting a slice of bytes to a string type yields a string whose successive bytes are the elements of the slice.

and

Converting a value of a string type to a slice of bytes type yields a slice whose successive elements are the bytes of the string.

Go strings can contain arbitrary byte sequences.