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
+16.2k Golang : Get sub string example
+29.8k Golang : Saving(serializing) and reading file with GOB
+8.4k Golang : Routes multiplexer routing example with regular expression control
+14.2k Golang : convert rune to unicode hexadecimal value and back to rune character
+9.1k Golang : Populate or initialize struct with values example
+13.3k Golang : Convert(cast) int to int64
+16.5k Golang : Find out mime type from bytes in buffer
+15k Golang : Reset buffer example
+7.7k Golang : Detect sample rate, channels or latency with PortAudio
+17.9k Golang : [json: cannot unmarshal object into Go value of type]
+15.4k Golang : Get timezone offset from date or timestamp