size of struct

3,129 views
Skip to first unread message

Don Dwoske

unread,
Jul 21, 2010, 9:11:45 PM7/21/10
to golang-nuts
I've searched this list and read the docs, and have come to the
conclusion that it's not possible (or not very easy) to find the
amount of memory a struct is using.

From the docs of unsafe.Sizeof:

func Sizeof(v ArbitraryType) int

Sizeof returns the size in bytes occupied by the value v. The size is
that of the "top level" of the value only. For instance, if v is a
slice, it returns the size of the slice descriptor, not the size of
the memory referenced by the slice.


When I do a Sizeof a struct, I always get 8, no matter how many fields
are in the struct.

Is there a way I can find out during runtime how much memory an
instance of a struct is using?

Daniel Smith

unread,
Jul 21, 2010, 9:20:50 PM7/21/10
to Don Dwoske, golang-nuts
Are you sure you're not passing in a pointer to your struct?


On Wed, Jul 21, 2010 at 8:11 PM, Don Dwoske <don.d...@gmail.com> wrote:
When I do a Sizeof a struct, I always get 8, no matter how many fields
are in the struct.


--
Daniel Smith
http://www.schaumburggoclub.org/

Rob 'Commander' Pike

unread,
Jul 21, 2010, 9:21:25 PM7/21/10
to Don Dwoske, golang-nuts
I'm pretty sure you're asking what the size of a pointer to a struct is. This code prints 16.

type T struct { a, b, c, d int }

func main() {
fmt.Println(unsafe.Sizeof(T{}))
}

Andrew Gerrand

unread,
Jul 21, 2010, 9:32:17 PM7/21/10
to Rob 'Commander' Pike, Don Dwoske, golang-nuts
On 22 July 2010 11:21, Rob 'Commander' Pike <r...@google.com> wrote:
> I'm pretty sure you're asking what the size of a pointer to a struct is.  This code prints 16.

Structs are allocated in 8-byte blocks on 64-bit systems:

adg ~/test$ cat sizeof.go
package main

import "unsafe"

type A struct { a int }
type B struct { a, b int }
type C struct { a, b, c int }
type D struct { a, b, c, d int }
type E struct { a, b, c, d, e int }

func main() {
println(unsafe.Sizeof(A{}))
println(unsafe.Sizeof(B{}))
println(unsafe.Sizeof(C{}))
println(unsafe.Sizeof(D{}))
println(unsafe.Sizeof(E{}))
}
adg ~/test$ ./6.out
8
8
16
16
24
adg ~/test$ ./8.out
4
8
12
16
20

This also might explain what Don is seeing.

Andrew

Don Dwoske

unread,
Jul 26, 2010, 8:01:26 PM7/26/10
to golang-nuts
Indeed that is what I was doing... silly me. I see a proper value
when dereferencing the pointer.

import "unsafe"
type E struct { a, b, c, d, e int }
func main() {
t := new(E)
println(unsafe.Sizeof(t)) // returns 8 - not what I want,
I was basically doing this.
println(unsafe.Sizeof(*t)) // returns 24 - what I was
looking for
}

Thanks to all who responded.

-Don


basically had a struct
Reply all
Reply to author
Forward
0 new messages