跳到內容

pointerof

pointerof 運算式會回傳一個 Pointer,它指向變數或實例變數的內容。

一個使用變數的範例

a = 1

ptr = pointerof(a)
ptr.value = 2

a # => 2

一個使用實例變數的範例

class Point
  def initialize(@x : Int32, @y : Int32)
  end

  def x
    @x
  end

  def x_ptr
    pointerof(@x)
  end
end

point = Point.new 1, 2

ptr = point.x_ptr
ptr.value = 10

point.x # => 10

由於 pointerof 涉及指標,因此被認為是不安全的