Go struct layout

239 views
Skip to first unread message

Rajiv Kurian

unread,
Jun 11, 2014, 4:28:30 PM6/11/14
to golan...@googlegroups.com
Sorry if this has been answered already. Where may I learn more about how stucts are laid out in Go? Does the standard say anything about the layout? With C++ this is usually compiler dependent but there are semi-decent tools (g++ -fdump-class-hierarchy etc) to visualize the layout. How does layout change (if at all) when a struct implements an interface? Where are the vtables stored? Is the struct layout altered because of book keeping needs for the GC?

Thanks,
Rajiv

Ian Lance Taylor

unread,
Jun 11, 2014, 4:39:14 PM6/11/14
to Rajiv Kurian, golang-nuts
On Wed, Jun 11, 2014 at 1:28 PM, Rajiv Kurian <geet...@gmail.com> wrote:
>
> Sorry if this has been answered already. Where may I learn more about how
> stucts are laid out in Go? Does the standard say anything about the layout?
> With C++ this is usually compiler dependent but there are semi-decent tools
> (g++ -fdump-class-hierarchy etc) to visualize the layout.

The Go language spec does not say anything about how structs are laid
out. As with C/C++, this is intentional. In particular, structs are
laid out differently for different architectures due to differing
alignment constraints. Also they are laid out differently for
different compilers--the gc and gccgo compilers do not have identical
struct layouts. So a precise answer to your question is architecture
and compiler dependent.

For a given architecture and compiler, it's easy enough to use
reflect, or simply unsafe.Offsetof and unsafe.Sizeof, to see exactly
how a struct is laid out in memory. I'm not sure that we promise that
struct layout will never change for different versions of a compiler,
but that said I can't think of any reason why it would change.


> How does layout change (if at all) when a struct implements an
> interface?

It does not change at all.


> Where are the vtables stored?

Go does not have vtables in the C++ sense. When you store a value
into an interface, the interface will get a pointer to the list of
methods that implement the interface's dynamic type.

A different way to answer your question: vtables are stored in the
type descriptor, which is essentially the value you get from calling
reflect.TypeOf.


> Is the struct layout altered because of book keeping needs
> for the GC?

No.

Ian

Rob Pike

unread,
Jun 11, 2014, 4:50:16 PM6/11/14
to Ian Lance Taylor, Rajiv Kurian, golang-nuts
Everything Ian said is correct (of course), but he left out the most
important part, which is that you shouldn't care about this issue at
all. If you need precise control of every byte of memory, Go is not
your language.

-rob

Rajiv Kurian

unread,
Jun 11, 2014, 5:01:57 PM6/11/14
to golan...@googlegroups.com, geet...@gmail.com
Got it. Thanks!
Reply all
Reply to author
Forward
0 new messages