unicode/utf16

Guided tour · Formatting & Strings · pkg.go.dev →

Encode and decode UTF-16 (surrogate pairs). Rarely needed in Go — mostly useful when crossing into Windows APIs or JS.

Encode and Decode

Encode — runes → uint16 code units

runes := []rune{'h', 'i', '🎉'}
units := utf16.Encode(runes)
fmt.Println(units)
Output
[104 105 55356 57225]

Decode — uint16 code units → runes

runes := utf16.Decode([]uint16{104, 105, 55356, 57225})
fmt.Println(string(runes))
Output
hi🎉

Surrogate helpers

IsSurrogate, EncodeRune, DecodeRune

hi, lo := utf16.EncodeRune('🎉')
r := utf16.DecodeRune(hi, lo)
fmt.Printf("%U %U -> %c\n", hi, lo, r)