如果我有A
的实例,实例变量是否实现为指针?换句话说,是否通过引用访问实例变量,即使使用Structs?
class A
@title = "the title"
@my_val = MyStruct.new
end
答案 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)