~/Working with Bytes in Go

Jan 12, 2023


Go has first class support for working with byte slices and the bytes package. A byte in Go is an alias for uint8.

Declaring bytes

1
b := []byte("hello")

Use the bytes.Buffer for building or reading byte data efficiently.

1
2
3
var buf bytes.Buffer
buf.Write([]byte("hi"))
fmt.Println(buf.String()) // output hi

Comparing two byte slices is done with bytes.Equal:

1
bytes.Equal([]byte("a"), []byte("a")) // true

To convert a string to bytes and vice versa:

1
2
3
str := "world"
b := []byte(str)
s := string(b)

For searching, use bytes.Contains:

1
bytes.Contains([]byte("golang"), []byte("go")) // true

To read or write files as bytes, use the io/ioutil or os packages:

1
2
data, _ := os.ReadFile("file.txt")
os.WriteFile("file2.txt", data, 0644)

Bytes are used for working directly with binary data, file I O, and efficient manipulation of strings. Consult the Go documentation for more utilities.

Tags: [go] [bytes]