Search code examples
crystal-lang

How are instance variables of a Class implemented in Crystal?


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

Solution

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