← All notes

Go unicode/utf16: encode and decode UTF-16 sequences

Answer: Package utf16 implements encoding and decoding of UTF-16 sequences, including surrogate pairs.

Encode and decode whole slices

Encode returns the UTF-16 encoding of a slice of Unicode code points.

Decode returns the Unicode code point sequence represented by a UTF-16 slice.

AppendRune appends the UTF-16 encoding of a rune to a uint16 buffer and returns the extended buffer.

If that rune is not a valid Unicode code point, AppendRune appends the encoding of U+FFFD.

Surrogate pairs and rune length

A surrogate pair encodes a single supplementary code point as two 16-bit words.

IsSurrogate reports whether a Unicode code point can appear in a surrogate pair.

EncodeRune returns the surrogate pair for a rune.

If the rune is not a valid code point or does not need a pair, EncodeRune returns U+FFFD, U+FFFD.

DecodeRune decodes a surrogate pair.

DecodeRune returns the Unicode replacement code point U+FFFD when the pair is not a valid UTF-16 surrogate pair.

RuneLen returns the number of 16-bit words in the UTF-16 encoding of a rune, or -1 if the rune is not valid to encode in UTF-16.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: The Go Authors, utf16 package - unicode/utf16; The Go Authors, utf16.go (source). BSD-3-Clause (https://go.dev/LICENSE). Copyright The Go Authors. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: The Go Authors, utf16 package - unicode/utf16; The Go Authors, utf16.go (source). BSD-3-Clause (https://go.dev/LICENSE). Copyright The Go Authors.

Cite this

Permanent ID: iil:note:2t4axz76

iinventedlight. 2026. "Go unicode/utf16: encode and decode UTF-16 sequences." iinventedlight Library, iil:note:2t4axz76, version of 2026-11-27. https://iinventedlight.com/library/notes/go-unicode-utf16/. License: CC-BY-4.0.

@misc{iil_note_2t4axz76,
  author = {{iinventedlight}},
  title = {{Go unicode/utf16: encode and decode UTF-16 sequences}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-27},
  url = {https://iinventedlight.com/library/notes/go-unicode-utf16/},
  note = {Permanent ID iil:note:2t4axz76. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/go-unicode-utf16.md.