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
+6.9k Golang : Get environment variable
+51.1k Golang : Check if item is in slice/array
+17.3k Golang : Parse date string and convert to dd-mm-yyyy format
+18.2k Golang : Example for RSA package functions
+15.1k Golang : ROT47 (Caesar cipher by 47 characters) example
+20.3k Golang : Read directory content with os.Open
+12.6k Golang : http.Get example
+20.5k Golang : Convert PNG transparent background image to JPG or JPEG image
+7.1k Golang : Example of custom handler for Gorilla's Path usage.
+13.3k Golang : Strings comparison
+50.5k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+11.3k Golang : Handle API query by curl with Gorilla Queries example