Standard library / bytes

bytes.ToValidUTF8()

Replaces each contiguous run of invalid UTF-8 bytes with replacement; replacement itself should be valid UTF-8 for valid output. Expected stdout: 'a?b\n'.

Formal Syntax & Structure

go syntaxgo
func ToValidUTF8(s, replacement []byte) []byte

Parameters & Attributes

NameTypeDescription
s[]byteInput text or sequence.
replacement[]byteReplacement for each run of invalid UTF-8 bytes.

Return Value

[]byte

Replaces each contiguous run of invalid UTF-8 bytes with replacement; replacement itself should be valid UTF-8 for valid output.

Working Example

Example Snippetgo
package main
import (  "bytes"  "fmt")
func main() {  fmt.Println(string(bytes.ToValidUTF8([]byte("a\xff\xfeb"), []byte("?"))))}
Go Reference