Reputation: 2764
If I have an instance of A
, are the instance variables implemented as pointers? In other words, are instance variables accessed by reference, even when using Structs?
class A
@title = "the title"
@my_val = MyStruct.new
end
Upvotes: 1
Views: 177
Reputation: 7326
@my_val
is a reference to the instance of MyStruct
on the stack. Checkout this example and notice the difference:
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)
Upvotes: 1