UTF-8 ValidString Rejects Bad Bytes
Screen text with utf8.ValidString, then walk runes with DecodeRuneInString to locate the first invalid byte and report its offset.
Code
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
good := "héllo, 世界"
fmt.Println("valid:", utf8.ValidString(good))
fmt.Println("runes:", utf8.RuneCountInString(good), "bytes:", len(good))
// 0xff never forms a valid UTF-8 sequence
bad := string([]byte{'o', 'k', 0xff, '!'})
fmt.Println("valid bad:", utf8.ValidString(bad))
// decode runes until RuneError with width 1 marks the bad byte
for i := 0; i < len(bad); {
r, size := utf8.DecodeRuneInString(bad[i:])
if r == utf8.RuneError && size == 1 {
fmt.Printf("invalid byte at %d: %#x\n", i, bad[i])
}
i += size
}
fmt.Println("rune count:", utf8.RuneCountInString(bad))
}What the code does
UTF-8 ValidString Rejects Bad Bytes keeps everything in the function main.
Repetition is confined to for i := 0; i < len(bad); — the rest of the file is straight-line.
What to watch for
- The runtime is the only requirement — no packages, no install.
Applying it
The file announces its steps in the output: valid:, runes:, valid bad:.
Statements that matter
r, size := utf8.DecodeRuneInString(bad[i:])
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.
FAQ
- What does UTF-8 ValidString Rejects Bad Bytes print when run?
- Running the file directly is enough — expect labeled output lines such as `valid:`, `runes:`, `valid bad:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.