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
+12k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+10.6k Golang : Convert decimal number(integer) to IPv4 address
+6.9k Golang : Handle Palindrome string with case sensitivity and unicode
+10.8k Golang : Convert a rune to unicode style string \u
+18.3k Golang : Determine if directory is empty with os.File.Readdir() function
+5.8k Golang : Output or print out JSON stream/encoded data
+5.8k Golang : How to fix html/template : "somefile" is undefined error?
+6.8k Golang : Scan files for certain pattern and rename part of the files
+8.1k Golang : Generate Codabar
+15.3k Golang : Send email and SMTP configuration example
+12.5k Golang : Check if an integer is negative or positive
+29.9k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions