Class 的实例变量如何在 Crystal 中实现?

How are instance variables of a Class implemented in Crystal?

如果我有一个 A 的实例,实例变量是作为指针实现的吗?换句话说,实例变量是否通过引用访问,即使在使用 Structs 时也是如此?

class A
  @title = "the title"
  @my_val = MyStruct.new
end

@my_val 是对堆栈上 MyStruct 实例的引用。查看此示例并注意区别:

struct MyStruct
  property x

  def initialize(@x : Int32)
  end
end

class A
  getter my_val = MyStruct.new(10)
end


# mutates a struct (passed by reference)
def method(a : A)
  a.my_val.x = 20
end

# does not mutate a struct (passed by value)
def method(s : MyStruct)
  s.x = 30
end

a = A.new
p a.my_val.x       #=> 10

a.method(a)
p a.my_val.x       #=> 20

a.method(a.my_val)
p a.my_val.x       #=> 20 (not 30)