Go value layout in memory — reading types from panic stack traces

A quick way to see how Go types are laid out in memory is to trigger a panic and read the stack trace.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

type AA struct {
A string
B map[string]string
}

func main() {
retFunc("1", []rune("222"), nil, AA{})
}

func retFunc(s string, sl []rune, it interface{}, a AA) int {
panic("ret int")
return 0
}

Run on the playground

When this runs, the panic prints stack information for the call site twice. Focus on the function arguments (note that panic only shows ten arguments; the rest are truncated):

main.retFunc(0x9edcf, 0x1, 0x1042ff9c, 0x3, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, ...)

That does not line up with the parameter list:

retFunc(s string, sl []rune, it interface{}, a AA) int

You can shrink the signature and try one type at a time until the pattern is clear. Here is the mapping:

  • map — one word (pointer to map header)
  • string — two words (pointer to data and length)
  • slice — three words (pointer to backing array, length, capacity)
  • interface — two words (pointer to type and pointer to data)
  • struct — fields laid out in order, each following its own representation

So the panic line decodes as:

1
2
3
4
5
6
7
main.retFunc(
0x9edcf, 0x1, // string s: data pointer and length
0x1042ff9c, 0x3, 0x3, // slice sl: pointer, len, cap
0x0, 0x0, // interface it: type pointer and data pointer
0x0, 0x0, 0x0, // struct a: string A (ptr, len), map B pointer
... // (hidden) return value int
)

References
Understanding panic output in Go
godata
interface

Questions? Leave a comment below or email: newbvirgil@gmail.com