What Is the Difference Between string and []byte in Go

string is immutable text data, while []byte is a mutable slice of raw bytes used for binary data or modification.

In Go, string is an immutable sequence of bytes, while []byte is a mutable slice of bytes. Use string for text data that shouldn't change and []byte for binary data or when you need to modify the content. Converting between them is straightforward but involves copying the data.

// Convert string to []byte
s := "hello"
b := []byte(s) // b is now [104, 101, 108, 108, 111]

// Convert []byte to string
b2 := []byte{104, 101, 108, 108, 111}
s2 := string(b2) // s2 is now "hello"