Welcome to your journey into the world of Go (Golang)! Today, we'll dive deep into understanding bytes and runes - two fundamental building blocks in Go programming. Let's get started!
In Go, a byte is the basic unit of data representation. It can hold any value from 0 to 255 and is represented as an 8-bit integer type.
package main
import "fmt"
func main() {
var byteVariable byte = 100
fmt.Printf("The byte value is: %d\n", byteVariable)
}In the code above, we have declared a variable byteVariable of type byte and assigned it a value of 100. The output will be:
The byte value is: 100
A rune is a 32-bit integer type in Go, used to represent Unicode characters. This allows Go to handle a wide range of characters from various languages, including emojis 😊!
package main
import "fmt"
func main() {
var runeVariable rune = '🦁'
fmt.Printf("The rune value is: %q\n", runeVariable)
}In the code above, we have declared a variable runeVariable of type rune and assigned it an emoji character. The output will be:
The rune value is: 🦁
Go provides built-in functions to convert between bytes and runes:
byte(r): Converts a rune to a byte.rune(b): Converts a byte to a rune.package main
import "fmt"
func main() {
byteVar := byte('a') // convert rune to byte
runeVar := rune(97) // convert byte to rune
fmt.Printf("Byte value: %d\n", byteVar)
fmt.Printf("Rune value: %q\n", runeVar)
}In the code above, we convert a rune 'a' to a byte and a byte 97 to a rune, and print both their values. The output will be:
Byte value: 97
Rune value: a
fmt.Printf function with %d and %q format specifiers, respectively.package main
import "fmt"
func main() {
var byteVar byte = 100
var runeVar rune = '🦁'
fmt.Printf("Byte value: %d\n", byteVar)
fmt.Printf("Rune value: %q\n", runeVar)
}In the code above, we print the byte and rune values using the fmt.Printf function. The output will be:
Byte value: 100
Rune value: 🦁
== operator.package main
import "fmt"
func main() {
var byteVar1 byte = 100
var byteVar2 byte = 100
var runeVar1 rune = '🦁'
var runeVar2 rune = '🦁'
fmt.Printf("Byte values are equal: %t\n", byteVar1 == byteVar2)
fmt.Printf("Rune values are equal: %t\n", runeVar1 == runeVar2)
}In the code above, we compare two byte and two rune variables and print the result using the fmt.Printf function. The output will be:
Byte values are equal: true
Rune values are equal: true
What is the difference in size between a byte and a rune in Go?
We hope this lesson has helped you understand bytes and runes in Go! Keep learning and practicing to become a master Go programmer. Happy coding! 💡💻🙌