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 Golang : Increment string example
+22.3k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+6.1k Golang : Accessing dataframe-go element by row, column and name example
+11.4k Elastic Search : Return all records (higher than default 10)
+21.3k Golang : untar or extract tar ball archive example
+9k Golang : Convert octal value to string to deal with leading zero problem
+13.4k Golang : Parsing or breaking down URL
+7.4k Golang : How to check if input string is a word?
+32.6k Golang : Call a function after some delay(time.Sleep and Tick)
+4.6k Golang : Display advertisement images or strings on random order
+7.2k Prevent Write failed: Broken pipe problem during ssh session with screen command
+12.1k Golang : Count number of runes in string