Golang : How to verify input is rune?
Problem :
You need to determine if the user input is a valid rune. How to do that?
Solution :
Use unicode/utf8.Valid()
function to check if the user input is a valid rune.
For example,
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
valid := []byte("Hello, 世界")
invalid := []byte{0xff, 0xfe, 0xfd}
fmt.Println(utf8.Valid(valid))
fmt.Println(utf8.Valid(invalid))
}
Output :
true
false
NOTE :
Depending on the input stream type, use utf8.Valid()
for handling byte array, utf8.ValidRune()
is for handling single rune and use utf8.ValidString()
for handling string.
References :
https://golang.org/pkg/unicode/utf8/#Valid
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.1k Golang : Display packages names during compilation
+5.6k Golang : Derive cryptographic key from passwords with Argon2
+5.2k Golang : How to solve "too many .rsrc sections" error?
+5.8k CloudFlare : Another way to get visitor's real IP address
+8.9k Golang : Find and replace data in all files recursively
+7.3k Golang : How to check variable or object type during runtime?
+7.6k Golang : Gaussian blur on image and camera video feed examples
+6.4k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+9.9k Golang : Intercept and process UNIX signals example
+5.9k Swift : substringWithRange() function example
+6.7k Gogland : Where to put source code files in package directory for rookie
+7.7k Golang : Sort lines of text example