how can i get a object's size

1,477 views
Skip to first unread message

四月份平民

unread,
Nov 6, 2011, 4:30:22 AM11/6/11
to golan...@googlegroups.com
If there is a type definition锟斤拷
 
type Example struct {
a byte
b, c int32
        d,e,f float32
        g,h,i, j [1234]byte
        .......
}

what can i do  to get the size of  a object of Example quickily锟斤拷

peterGo

unread,
Nov 6, 2011, 11:04:44 AM11/6/11
to golang-nuts
package main

import (
"fmt"
"unsafe"
)

type T struct {
a byte
b, c int32
d, e, f float32
g, h, i, j [1234]byte
}

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

Output: 4960

Peter

Kal

unread,
Nov 6, 2011, 1:22:22 PM11/6/11
to golan...@googlegroups.com
Be careful if your struct contains slices. Sizeof will include the size of the slice data type, not the underlying data ie. flatten the structure like gob encoding will.

fango

unread,
Nov 6, 2011, 6:52:15 PM11/6/11
to golang-nuts
For those cannot use package unsafe, http://play.golang.org/p/L3q1R2E-QJ
package main
import ("fmt")

type T struct {
a byte
b, c int32
d,e,f float32
g,h,i, j [1234]byte
}

var a [2]T
func main(){
p0 := &a[0]
p1 := &a[1]
s := fmt.Sprintf("%p %p", p1, p0)
var i0, i1 int
fmt.Sscanf(s, "0x%x 0x%x", &i1, &i0)
fmt.Printf("%s = %d\n", s, i1 - i0)
}

John Asmuth

unread,
Nov 6, 2011, 7:15:15 PM11/6/11
to golan...@googlegroups.com
That seems unreliable. I don't believe there is a guarantee that the compiler won't pad the data in the array to make it align to something convenient.

mikespook

unread,
Nov 7, 2011, 12:39:00 AM11/7/11
to golan...@googlegroups.com
also, the "reflect" package can resolve this. http://play.golang.org/p/p4A_RoA6Gt

package main

import (
    "fmt"
    "reflect"
)

type T struct {

    a byte
    b, c int32
        d,e,f float32
        g,h,i, j [1234]byte   
}

var a T
func main(){
    t := reflect.TypeOf(a)
    fmt.Printf("Sizeof(T) = %d Byte", t.Size())
}
Reply all
Reply to author
Forward
0 new messages