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

时间:2017-12-06 02:12:28

标签: crystal-lang

如果我有A的实例,实例变量是否实现为指针?换句话说,是否通过引用访问实例变量,即使使用Structs?

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

1 个答案:

答案 0 :(得分:1)

@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)