Distinguish private representations from stable APIs
Distinguish private representations from stable APIs
The Go specification defines observable language behavior; public package documentation defines API contracts. Runtime source files explain a particular implementation. Private fields, compiler ABI, linkname targets and undocumented pointer layouts may change between releases or architectures. A program that reads private map or channel headers can silently break even when ordinary Go code continues to work. Prefer a public API, and use version-pinned diagnostics only for investigation. Never retain a uintptr as a substitute for a live Go pointer.
package main
import ( "fmt" "maps" "slices")
func main() { src := []int{1, 2, 3} copyOf := slices.Clone(src) copyOf[0] = 9 fmt.Println(src, copyOf) m := map[string]int{"a": 1} n := maps.Clone(m) n["a"] = 2 fmt.Println(m["a"], n["a"])}The public Clone functions copy slice elements or map entries. They are shallow copies: nested reference-like values can still alias. These APIs are available from Go 1.21; they avoid any dependency on header structure. Use explicit deeper copies only when the ownership contract requires them.
Expected output:
[1 2 3] [9 2 3]1 2Choose a documented wire representation
package main
import ( "encoding/binary" "fmt")
func main() { var b [4]byte binary.BigEndian.PutUint32(b[:], 0x01020304) fmt.Printf("%x %d\n", b, binary.BigEndian.Uint32(b[:]))}The wire format defines four bytes and big-endian order independently of native struct padding or CPU byte order. Decode only after validating the required input length. When upgrading Go, test public invariants on all supported targets and record go version and GOARCH for diagnostics. A successful build alone does not establish semantic or binary compatibility with private runtime layouts.
Expected output:
01020304 16909060Try it locally
Write a public decoder for exactly two big-endian bytes. Reject other lengths; show output for [0,42] and [1].
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime representations 06: Distinguish private representations from stable APIs
Check the lesson objective before moving on.
Which is a reliable dependency for portable application logic?
What does maps.Clone guarantee about nested slice values?