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
+21.2k Golang : Get password from console input without echo or masked
+5.3k PHP : See installed compiled-in-modules
+21.9k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+26.2k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+18.9k Golang : Implement getters and setters
+8.4k Golang : Check if integer is power of four example
+22.3k Golang : How to run Golang application such as web server in the background or as daemon?
+5.8k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+16.4k Golang : convert string or integer to big.Int type
+40.2k Golang : UDP client server read write example
+7.9k Golang : Regular Expression find string example
+6.6k Elasticsearch : Shutdown a local node