Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #109 Number of bytes of a type

Set n to the number of bytes of a variable t (of type T).

import "reflect"
var t T
tType := reflect.TypeOf(t)
n := tType.Size()

This run-time reflection works on a value of the type T.
Note that the size does not include the memory indirectly taken by the reference fields: Strings, slices, etc.
Warning: for a given program, the size of a type is not the same on a 32-bit machine or a 64-bit machine.
N : Integer := (T'Size + 7) / 8;

T'Size returns size of T in bits. It is the minimum number of bits required to store an object of that type.
Divide by 8 to convert to bytes

New implementation...
< >
programming-idioms.org