💻 Tech
If you’re traversing a slice of bytes of string in Go, and you want to decode each byte into a rune, it’s possible to encounter a non-printable character. For example, if you’re using %c directive in a for loop, the iteration with a non-printable character will be skipped. To check if a character is printable, you can use the unicode.IsPrint function. Here’s an example:
s := "Hello ☺"
for _, r := range s {
if unicode.IsPrint(r) {
fmt.Printf("%c", r)
}
}
One real-world example where it happens is when you try to decode a byte that is part of a multi-byte character. For example, smiley face ☺ occupies 3 bytes in UTF-8 encoding.