type Req struct{
header Head
body Body
}
type Head struct{
length uint32
sequence uint32
}
type Body struct{
entitySize uint32
entity []Entity
}
type Entity struct{
id uint32
status uint16
}func main() {
e1 := Entity{}
e2 := Entity{}
v := Req{}
v.body.entity = append(v.body.entity, e1)
v.body.entity = append(v.body.entity, e2)
fmt.Println(binary.Size(v))
// this output is -1.
}
// this function is from modified binary size() function
func sizeof(t reflect.Type) int {
switch t.Kind() {
case reflect.Array:
fmt.Println("reflect.Array")
if s := sizeof(t.Elem()); s >= 0 {
return s * t.Len()
}
case reflect.Struct:
fmt.Println("reflect.Struct")
sum := 0
for i, n := 0, t.NumField(); i < n; i++ {
s := sizeof(t.Field(i).Type)
if s < 0 {
return -1
}
sum += s
}
return sum
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
fmt.Println("reflect.int")
return int(t.Size())
case reflect.Slice:
//modified place
fmt.Println("reflect.Slice:", sizeof(t.Elem()))
return 0
}
return -1
}
type Req struct{
header Head
body Body
}
type Head struct{
length uint32
sequence uint32
}
type Body struct{
entitySize uint32
entity []Entity
}
type Entity struct{
id uint32
status uint16
}
func main() {
e1 := Entity{}
e2 := Entity{}
e3 := Entity{}
v := Req{}
v.body.entity = append(v.body.entity, e1)
v.body.entity = append(v.body.entity, e2)
v.body.entity = append(v.body.entity, e3)
base := sizeof(reflect.TypeOf(v))
variable := len(v.body.entity ) * sizeof(reflect.TypeOf(e3))
fmt.Println(base + variable)
}
Why don't you just use reflect.Type.Size()? Do you need to chase the pointer in the slice headers recursively?
--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/Bq4c-1nvmCw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.