Go has integer types called byte and rune epithets for uint8 and int32 data types. In Go, there is no char data type. Instead, it uses byte and rune to represent character values. The []byte and string in Go are small headers pointing to data that have lengths suggesting how much data is present. The []byte has two lengths:
- The current length of the data.
- Capacity.
A byte is one of the most used data types in Go, and let’s create one.
How to Create a byte in Go
To create a byte in Go, assign an ASCII character to a variable. A byte in Golang is an unsigned 8-bit integer.
The byte type represents ASCII characters, while the rune data type represents a broader set of Unicode characters encoded in UTF-8 format.
package main
import (
"fmt"
)
func main() {
var b1 byte = 65
var b2 byte = 66
fmt.Println(b1)
fmt.Println(b2)
}
Output
65
66
To convert these ASCII numbers to characters, use the Printf(“%c”).
package main
import (
"fmt"
)
func main() {
var b1 byte = 65
var b2 byte = 66
fmt.Printf("%c\n", b1)
fmt.Printf("%c\n", b2)
}
Output
A
B
How to Create a byte array in Golang
To create a byte array in Golang, use a slice of bytes []byte. Golang’s slice data type provides a suitable and efficient way of working with typed data sequences.
Syntax
[]byte("Your String")
Example
package main
import (
"fmt"
)
func main() {
byteArray := []byte{97, 98, 99, 100, 101, 102}
fmt.Println(byteArray)
}
Output
[97 98 99 100 101 102]
For converting from a string to a byte slice, string -> []byte.
To convert a byte array to a string, use the string() constructor.
That’s it for this tutorial.
More posts

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.