有条件的同学看一下官方,我这也是那抄的:https://golang.org/pkg/unicode/utf8/#ValidString
func Valid(p []byte) bool
Valid reports whether p consists entirely of valid UTF-8-encoded runes.
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))
}
func ValidRune(r rune) bool
ValidRune reports whether r can be legally encoded as UTF-8. Code points that are out of range or a surrogate half are illegal.
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
valid := 'a'
invalid := rune(0xfffffff)
fmt.Println(utf8.ValidRune(valid))
fmt.Println(utf8.ValidRune(invalid))
}
有疑问加站长微信联系(非本文作者)