alignof

The alignof expression returns an Int32 with the ABI alignment in bytes of a given type. For example:

  1. alignof(Int32) # => 4
  2. alignof(Int64) # => 8
  3. struct Foo
  4. def initialize(@x : Int8, @y : Int16)
  5. end
  6. end
  7. @[Extern]
  8. @[Packed]
  9. struct Bar
  10. def initialize(@x : Int8, @y : Int16)
  11. end
  12. end
  13. alignof(Foo) # => 2
  14. alignof(Bar) # => 1

For Reference types, the alignment is the same as the alignment of a pointer:

  1. # On a 64 bits machine
  2. alignof(Pointer(Int32)) # => 8
  3. alignof(String) # => 8

This is because a Reference’s memory is allocated on the heap and a pointer to it is passed around. To get the effective alignment of a class, use instance_alignof.

The argument to alignof is a type and is often combined with typeof:

  1. a = 1
  2. alignof(typeof(a)) # => 4