跳到內容

alignof

alignof 表達式會回傳一個 Int32,表示給定類型在 ABI 中的對齊位元組數。例如:

alignof(Int32) # => 4
alignof(Int64) # => 8

struct Foo
  def initialize(@x : Int8, @y : Int16)
  end
end

@[Extern]
@[Packed]
struct Bar
  def initialize(@x : Int8, @y : Int16)
  end
end

alignof(Foo) # => 2
alignof(Bar) # => 1

對於 參考 類型,對齊方式與指標的對齊方式相同。

# On a 64-bit machine
alignof(Pointer(Int32)) # => 8
alignof(String)         # => 8

這是因為 Reference 的記憶體配置在堆積上,並且會傳遞指向它的指標。若要取得類別的有效對齊方式,請使用 instance_alignof

alignof 的引數是一個 類型,並且通常會與 typeof 結合使用。

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