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
+7.1k Prevent Write failed: Broken pipe problem during ssh session with screen command
+9.5k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+27.8k Golang : Save map/struct to JSON or XML file
+10.8k Golang : Perform sanity checks on filename example
+5.9k Mac OSX : Find large files by size
+14.2k Golang : Get current time from the Internet time server(ntp) example
+10.5k Golang : Find and draw contours with OpenCV example
+12.7k Golang : Get current time
+9.9k Android Studio : Create custom icons for your application example
+5.4k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+32.1k Golang : Converting a negative number to positive number
+18.3k Golang : Close channel after ticker stopped example