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
+5.3k Golang : Reclaim memory occupied by make() example
+9.5k Golang : Get all countries currencies code in JSON format
+9.2k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+9.9k Golang : Turn string or text file into slice example
+7k Golang : Takes a plural word and makes it singular
+5.3k Golang : How to deal with configuration data?
+7.7k Golang : How to execute code at certain day, hour and minute?
+9.3k Golang : How to get garbage collection data?
+12.3k Golang : How to check if a string starts or ends with certain characters or words?
+8.4k Golang : How to check if input string is a word?
+4.9k JQuery : Calling a function inside Jquery(document) block
+23.1k Golang : Print out struct values in string format