How do I validate UTF-8 strings?

This example demonstrates how to validate UTF-8 strings in Go using the unicode standard library.
utf-8, validation, go, unicode, programming

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    // Example strings
    validUTF8 := "Hello, 世界"
    invalidUTF8 := []byte{0xff, 0xfe, 0xfd}

    // Validate validUTF8
    if utf8.ValidString(validUTF8) {
        fmt.Println("Valid UTF-8 string:", validUTF8)
    } else {
        fmt.Println("Invalid UTF-8 string:", validUTF8)
    }

    // Validate invalidUTF8
    if utf8.Valid(invalidUTF8) {
        fmt.Println("Valid UTF-8 byte sequence")
    } else {
        fmt.Println("Invalid UTF-8 byte sequence")
    }
}
    

utf-8 validation go unicode programming