Inspect slices, strings and interface metadata
Inspect slices, strings and interface metadata
A slice describes a view of an underlying array; its length is the accessible element count and capacity describes how far it may extend. In Go 1.23 the runtime slice descriptor contains a data pointer, length and capacity; the string descriptor contains a data pointer and byte length. Empty and nonempty interfaces use different internal descriptors carrying type or method-table information and data. These are private representations, not portable struct definitions. Use len, cap, reflect.TypeOf and type assertions instead of reinterpreting their memory.
package main
import ( "fmt" "unicode/utf8")
func main() { a := [4]int{1, 2, 3, 4} s := a[1:3] s[0] = 9 fmt.Println(len(s), cap(s), a) t := "سلام" fmt.Println(len(t), utf8.RuneCountInString(t))}The slice shares the array; the capacity starts at index 1. The UTF-8 string has eight bytes but four runes. unsafe.Sizeof(s) measures the descriptor only, not the array; the string size likewise excludes backing bytes. Strings are immutable; do not turn string data into writable bytes. An append may reuse the array or allocate another one depending on capacity.
Expected output:
2 3 [1 9 3 4]8 4Dynamic type versus nil interface
package main
import ( "fmt" "reflect")
type Item struct{ ID int }
func main() { var p *Item var x any = p fmt.Println(x == nil, reflect.TypeOf(x).Kind(), reflect.ValueOf(x).IsNil()) var y any fmt.Println(y == nil, reflect.TypeOf(y) == nil)}The first interface contains the dynamic type *Item and a nil pointer value. The second has no dynamic type or value. Check the kind before calling IsNil, which is not valid for every kind. The example observes public behavior without reading interface words or assuming that all values are boxed in the same way.
Expected output:
false ptr truetrue trueTry it locally
Create a full slice expression with capacity equal to length; append a value and show that the original array is unchanged. Use array [4]int{1,2,3,4} and slice a[1:3:3].
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime representations 01: Inspect slices, strings and interface metadata
Check the lesson objective before moving on.
What does unsafe.Sizeof on a slice value measure?
Why is an any holding a nil *Item not nil?